Wednesday, 3 September 2014

Consecutive prime sum Problem 50 The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953. Which prime, below one-million, can be written as the sum of the most consecutive primes?

//Answer=997651
checkprime(int k)
{int p=0;
int n=2;
while(n<=k/2)
{
if(k%n==0){p++;}
n++;
}
if(p==0){return 1;}
else{return 0;}
}
main(){
long long int x=2;
long long int n=0;
long long int sum=0;
long long int large=0;
long long int res=0;
while(x<1000000)
{while(x<1000000)
{
    if(checkprime(x)==1){break;}
    x++;
}


    int k=x;
    while(sum<1000000)
{
sum+=k;
n++;
if(sum>1000000){sum-=k;n--;break;}
while(k<1000000)
{
k++;
if(checkprime(k)==1){break;}
}}
while(checkprime(sum)!=1&&sum>0){
while(1)
{
k--;
if(checkprime(k)==1){break;}
}
sum-=k;
n--;
}
if(n>large){large=n;res=sum;}
sum=0;x++;n=0;
}




printf("%d",res);
}

No comments:

Post a Comment