Sunday, February 5, 2012

sum of all primes between 2 and 20 million

/*
 * bhatt.umang7@gmail.com
 */
/*
 * The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
 * Find the sum of all the primes below two million.
 */
#include<stdio.h>
void calculate_prime_sum() 
{

    unsigned int max = 2000000;
    long long int ans = 2 ;  // as 2 is special case we are directly adding 2 to it


    long int i=0;
    long int j=0;

    int tmp=0;
    for(i=3;i<max;i+=2) 
    {

        for(j=3;j*j<=i;j++) 
        {
            if((i%j)==0) 
            { 
                tmp=1; 
                break;
            }
        }

        if(tmp==0) 
        { 
            ans = ans+ i ;
        } 
        else 
            tmp=0;
    }

 printf("%lld",ans);
}

main()
{
    calculate_prime_sum();
}    

No comments:

Post a Comment