Skip to content

Commit 334cab4

Browse files
committed
feat(euler44): look ahead checking saves iterations
1 parent 85780e0 commit 334cab4

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

Project-Euler/Problem044.js

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,17 @@ function problem44(k) {
2222

2323
for (let j = k - 1; j > 0; j--) {
2424
const m = (j * (3 * j - 1)) / 2 // calculate all Pj < Pk
25-
if (isPentagonal(n - m) && isPentagonal(n + m)) {
26-
// Check sum and difference
27-
return n - m // return D
25+
// Check forward, checking n - m doubles work from previous iterations
26+
const sum = n + m
27+
if (isPentagonal(sum)) {
28+
// Check sum - m = n
29+
if (isPentagonal(sum + m)) {
30+
return n // return D
31+
}
32+
// Check sum - n = m
33+
if (isPentagonal(sum + n)) {
34+
return m // return D
35+
}
2836
}
2937
}
3038
}

0 commit comments

Comments
 (0)