-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem044.py
45 lines (32 loc) · 1.08 KB
/
Problem044.py
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
"""
Project Euler Problem 44
========================
Pentagonal numbers are generated by the formula, P[n]=n(3n-1)/2. The first
ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P[4] + P[7] = 22 + 70 = 92 = P[8]. However, their
difference, 70 - 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, P[j] and P[k], for which their sum
and difference is pentagonal and D = |P[k] - P[j]| is minimised; what is
the value of D?
"""
from math import sqrt, floor
def P_n(n):
return n*(3*n-1) // 2
def is_pentagonal(Pn):
""" Solving the quadratic expression we can determine n and see is integer """
n = (1/2 + sqrt(1/4+4*3/2*Pn))/3
return floor(n) == n
found = False
n = 0
pentagons = set()
difference = {}
while not found:
n += 1
new_pentagon = P_n(n)
for pentagon in pentagons:
if new_pentagon - pentagon in pentagons and is_pentagonal(new_pentagon+pentagon):
print(new_pentagon-pentagon)
found = True
break
pentagons.add(new_pentagon)