-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem44.py
More file actions
50 lines (41 loc) · 1.32 KB
/
problem44.py
File metadata and controls
50 lines (41 loc) · 1.32 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
45
46
47
48
"""
Pentagon numbers
Project Euler Problem #44
by Muaz Siddiqui
Pentagonal numbers are generated by the formula, Pn=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 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 are pentagonal and D = |Pk − Pj| is minimised; what is the value of D?
"""
from euler_helpers import timeit
import math
def pentagonal(n):
return n*(3*n-1)/2
def is_pentagonal(num):
if num < 0 :
return False
pent = (((24*num) + 1)** 0.5 + 1)/6
return pent == math.floor(pent)
@timeit
def answer():
#Let's assume this pair is within the first 10000 pentagonal numbers
pentagonals = []
for n in range(1, 10001):
pentagonals.append(int(pentagonal(n)))
smallest = 0
# count up from k and down from j
k = 1
while not smallest:
k += 1
pent_k = pentagonals[k]
j = k - 1
while j > 0:
pent_j = pentagonals[j]
first = pent_j + pent_k
next = pent_k - pent_j
if is_pentagonal(first) and is_pentagonal(next):
smallest = next
break
j -= 1
return smallest