问题:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
答案:
142913828922
#include
#include
#include
int isPrime(int n)
{
if(1 == n) return 0;
else if(4 > n ) return 1;
else if(0 == (n%2)) return 0;
else if(9 > n) return 1; //4, 6, 8 is excluded by row 7;
else if(0 == (n%3)) return 0;
else {
int r = ( int)floor(sqrt((double)n));
int f = 5;
while(f <= r){
if(0 == (n%f)) return 0;
if(0 == (n%(f+2))) return 0;
f += 6;
}
return 1;
}
}
int main(void)
{
const int limit = 2000000;
double sum=5.0;
int n = 5;
while(n<=limit)
{
if(isPrime(n))
sum += (double)n;
n +=2;
if(n<=limit && isPrime(n))
sum += (double)n;
n +=4;
}
printf("%f\n", sum);
return 0;
}
/* The answer is 142913828922 */
阅读(698) | 评论(0) | 转发(0) |