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?
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.
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.
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.
In mathematics, the sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to any given limit.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With