Difficulty rating is 5%.
The task is to calculate all prime numbers below 2 million.
The solution is straightforward: use the Sieve of Eratosthenes to find primes below 2 million.
There are several algorithms to check if a number is prime, such as Miller-Rabin and AKS.
However, for this problem, I believe the Sieve of Eratosthenes is the best approach.
#include <stdio.h>
#include <stdint.h>
int main()
{
int primes[200000];
int count = 0;
int64_t sum = 0;
primes[count++] = 2;
sum += 2;
primes[count++] = 3;
sum += 3;
for( int i = 5 ; i < 2000000 ; i+=2 )
{
int j;
for( j = 1; primes[j]*primes[j] <= i ; j++ )
{
if( i%primes[j] == 0 ) break;
}
if( i%primes[j] )
{
primes[count++] = i;
sum += i;
}
}
printf("Ans = %jd\n", sum);
}
'Programming > Project Euler' 카테고리의 다른 글
508. Project Euler #508 : integers in base i-1 (0) | 2015.05.02 |
---|---|
510. Project Euler #510 : Tangent circles. (0) | 2015.04.22 |
9, Project Euler #9 : Special Pythagorean triplet (0) | 2015.04.20 |
Current my project euler status. (0) | 2015.04.16 |
8. Project Euler #8 : Largest product in a series. (0) | 2015.04.16 |