-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path050.js
More file actions
82 lines (72 loc) · 1.85 KB
/
050.js
File metadata and controls
82 lines (72 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
// 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?
function isPrime(n) {
if (n < 2) return false;
var q = Math.floor(Math.sqrt(n));
for (var i = 2; i <= q; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
function nthPrime(n) {
var num = 1;
var i = 0;
while (i < n) {
num++;
while (!isPrime(num)) {
num++;
}
i++;
}
return num;
}
var nthPrimeMemo = (function(){
var memo = [];
return function(n) {
var num = memo[n];
if (typeof num === 'undefined') {
num = nthPrime(n);
memo[n] = num;
}
return num;
};
})();
function sumConsecutivePrimes(start, n) {
var sum = nthPrime(start);
var cnt = 1;
while (cnt < n) {
sum += nthPrime(start + cnt);
cnt++;
}
return sum;
}
function maxStreak(limit) {
var maxStart = 1, maxLength = 1, prime = 2;
var start = 1;
var length, sum;
while (nthPrimeMemo(start) < limit) {
length = 1;
sum = sumConsecutivePrimes(start, length);
while (sum < limit) {
if (isPrime(sum) && length > maxLength) {
maxStart = start;
maxLength = length;
prime = sum;
}
length++;
sum = sumConsecutivePrimes(start, length);
}
start++;
}
return prime;
}
//FIXME Find dynamic programming solution
console.log( maxStreak(1000000) );