标签:c++ project euler
The prime 41, can be written as the sum of six consecutive primes:
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?
#include <iostream>
#include <vector>
using namespace std;
int a[1000000];
int asize = 0;
bool isPrime[1000000] = { false };
bool prim(int n)
{
int i;
for (i = 2; i * i <= n; i++)
{
if (n % i == 0)
return false;
}
return true;
}
void init()
{
int i, j;
i = 3;
j = 1;
a[0] = 2;
while (1)
{
if (prim(i))
{
isPrime[i] = true;
a[j++] = i;
if (i >= 1000000)
{
asize = j;
break;
}
}
i += 2;
}
}
int main()
{
init();
int maxn;
int maxlen = 0;
for (int n = 1000; n < 1000000; n++)
{
if (isPrime[n])
{
for (int i = 0; i < asize; i++)
{
int len = 0;
int sum = 0;
if (a[i]>n)
break;
for (int j = i;; j++)
{
sum += a[j];
len++;
if (sum > n)
break;
if (sum == n)
{
if (len > maxlen)
{
maxlen = len;
maxn = n;
}
}
}
}
}
}
cout << maxn << " " << maxlen << endl;
system("pause");
return 0;
}Project Euler:Problem 50 Consecutive prime sum
标签:c++ project euler
原文地址:http://blog.csdn.net/youb11/article/details/46400513