forked from dhruvbaldawa/project_euler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0044-pentagonal-sum-difference.py
36 lines (28 loc) · 1 KB
/
0044-pentagonal-sum-difference.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
"""
Problem 44
Pentagonal numbers are generated by the formula, Pn=n(3n1)/2. The first
ten pentagonal numbers are:
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their difference,
70 - 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, Pj and Pk, for which their sum and
difference is pentagonal and D = |Pk - Pj| is minimised; what is the value of D?
"""
import math
def is_pentagonal(x):
n = (math.sqrt((24 * x) + 1) + 1) / 6
if n == int(n) and n > 0:
return True
return False
def brute_force():
start = 1
n = 1
pentagonal = lambda x: x * (3 * x - 1) / 2
limit = 3000
p_list = [pentagonal(n) for n in range(1, limit)]
for i in range(start, len(p_list)):
for j in range(i, len(p_list)):
if is_pentagonal(p_list[i] + p_list[j]) and \
is_pentagonal(abs(p_list[i] - p_list[j])):
print p_list[i], p_list[j], p_list[i] - p_list[j]
print "Answer:", brute_force()