-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem044.cpp
44 lines (41 loc) · 1.11 KB
/
problem044.cpp
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
#include <cmath>
#include <iostream>
#include <limits>
bool isPentagonal(long long n)
{
return fmod(sqrt(24 * n + 1), 6) == 5;
}
long long minimalDifference()
{
long long minD = std::numeric_limits<long long>::max();
long long current = 5;
long long inc = 7;
// The outer loop generates pentagonal numbers until the distance to the
// next number exceeds the recorded minimal difference. After that point,
// all differences will be greater than the recorded minimal difference,
// meaning it is the true minimal difference.
while (inc < minD) {
long long p = current - (inc - 3);
long long dec = inc - 6;
do {
long long d = current - p;
if (d >= minD) {
break;
}
if (isPentagonal(d) && isPentagonal(current + p)) {
minD = d;
break;
}
p -= dec;
dec -= 3;
} while (p >= 1);
current += inc;
inc += 3;
}
return minD;
}
int main()
{
std::cout << "Answer: " << minimalDifference() << '\n';
return 0;
}