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?
#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; }
时间: 2024-10-16 22:17:03