Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird situation in prime number checking code

When I was solving a problem for Project Euler, it asked me to sum up all the primes below 2 million. Here is my code:

#include<stdio.h>
#include<math.h>
int isPrime(int);
int main() {
    long long int sum = 0;
    int i; // index
    for(i = 2 ; i < 2000000 ; i++) {
        if(isPrime(i)) {
            sum += i;
        }
    }
    printf("%lli\n", sum);
}

int isPrime(int num) {
    int i; // index
    int sq = sqrt(num);
    for(i = 2 ; i <= sq ; i++) {
        if(num % i == 0) {
            return 0;
        }
    }
    return 1;
}

This code leads to the correct answer, 142913828922. But when I change the for loop in isPrime() to:

for(i = 2; i <= sq+1; i++)   // or even sq+2, sq+3, etc.

It leads to incorrect results such as 142913828920 and 142913828917, etc.

Why does it go wrong? Theoretically, it doesn't change the number isPrime() sends to main(), does it?

like image 292
lylec Avatar asked Jan 24 '16 08:01

lylec


People also ask

What is the condition to check prime number?

A prime number is a number that is divisible by only two numbers: 1 and itself. So, if any number is divisible by any other number, it is not a prime number.

What is the fastest way to check if a number is prime?

Simple methods. The simplest primality test is trial division: given an input number, n, check whether it is evenly divisible by any prime number between 2 and √n (i.e. that the division leaves no remainder). If so, then n is composite. Otherwise, it is prime.

Why do we use n 2 in prime numbers?

To factor the number n you have to divide by two other integers, call them a and b . Both of those numbers need to be 2 or larger, so it doesn't make any sense to check numbers larger than n/2 , they couldn't possibly divide evenly.

What is the algorithm for prime numbers?

In mathematics, the sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit.


2 Answers

if you change the loop to

for(i = 2 ; i <= sq+1 ; i++)

then 2 is no longer considered to be prime, because you test if 2 % 2 == 0.

Similar for larger numbers you add, more and more primes will not be detected as such.

like image 152
Henry Avatar answered Sep 27 '22 19:09

Henry


Considering you changed the sum from 142913828922 to 142913828920, then the difference is 2, which means you're interpreting 2 as not prime. Changing sq to sq+1 should achieve that difference. Changing it to sq+2 would end up making 3 not prime.

((int)sqrt(2))+1 == 2
((int)sqrt(3))+2 == 3

and so on.

like image 32
Patrick Roberts Avatar answered Sep 27 '22 18:09

Patrick Roberts