본문 바로가기
Programming/Project Euler

10. Project Euler #10 : Sum of primes

by 작은별하나 2015. 4. 21.

Difficulty rating is 5%.

 

This problem is calculate the primes below 2 million.

 

The solution is very simple.  Get primes below 2 million using sieve of Eratosthenes.

There are some Determining algorithms whether number is prime. Miller-rabin, AKS, etc.

In order to solve this problem, I think using sieve of Eratosthenes is best.

 

#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);
}

 

댓글