- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem044.cpp
More file actions
Latest commit
44 lines (41 loc) · 1.11 KB
/
Copy pathproblem044.cpp
File metadata and controls
44 lines (41 loc) · 1.11 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
#include<cmath>
#include<iostream>
#include<limits>
boolisPentagonal(longlong n)
{
returnfmod(sqrt(24 * n + 1), 6) == 5;
}
longlongminimalDifference()
{
longlong minD = std::numeric_limits<longlong>::max();
longlong current = 5;
longlong 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) {
longlong p = current - (inc - 3);
longlong dec = inc - 6;
do {
longlong 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;
}
intmain()
{
std::cout << "Answer: " << minimalDifference() << '\n';
return0;
}