When I solved the problem for Project Euler, he asked me to bring all 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.
This leads to incorrect results, such as 142913828920 and 142913828917, etc.
Why is everything going wrong? Theoretically, it does not change the number isPrime() sends to main() , right?
c algorithm primes
quartercat
source share