Computer Science/Algorithm

[Algorithm/C] Project Euler. Summation of primes

재오니소스 2017. 12. 15. 16:30

Summaion_of_primes.c

Click to download.



The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

/*

https://projecteuler.net/problem=10

Summation of primes

Writer : Mun Jae In

Date : 2017.12.15

*/


#include <stdio.h>

#include <math.h>


int isPrime(int n)

{

if(n==1)

{

return 0;

}

else if(n<4)

{

return 1;

}

else if(n%2==0)

{

return 0;

}

else if(n<9)

{

return 1;

}

else if(n%3==0)

{

return 0;

}

else

{

double r = floor(sqrt((double)n));

int f = 5;

while (f<=r)

{

if(n%f==0)

{

return 0;

}

else if(n%(f+2)==0)

{

return 0;

}

f += 6;

}

return 1;

}

}


int main(int argc, char * argv[])

{

int candidate = 1;

long long sum=0;


while(1)

{

candidate += 1;

if(isPrime(candidate))

{

sum += candidate;

}

if(candidate>=2000000) break;

}

printf("candidate : %d\n",candidate);

printf("sum : %lld\n",sum);

}


접근방법

1.앞에 풀었던 10001번째 소수 찾는 문제(바로가기)의 변형


문제 출처(바로가기)