-
Notifications
You must be signed in to change notification settings - Fork 0
/
p044.py
65 lines (48 loc) · 1.52 KB
/
p044.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 2 09:00:49 2020
@author: zhixia liu
"""
"""
Project Euler 44: Pentagon numbers
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?
"""
#%% naive
from tqdm import tqdm
from math import sqrt
def isPentagonal(m):
t = (1+sqrt(1+24*m))/6
return t.is_integer()
pentagonal_lst = [n*(3*n-1)/2 for n in range(1,10000)]
results = []
for m in tqdm(range(1,5000)):
for i in range(5000-m):
a=pentagonal_lst[i+m]
b=pentagonal_lst[i]
if isPentagonal(a-b) and isPentagonal(a+b):
results.append((a,b))
break
print(results)
print(min(results,key=lambda x: x[0]-x[1]))
#%% others
import sys
def NaturalNumbers():
n=1
while True:
yield n
n += 1
def P(n): # pentagonal
return (3*n*n-n)/2
def isdoubleP( x): # where `x' is P(m)+P(k) or P(m)-P(k)
q, r = divmod( x, 2)
return r == 0 and isPentagonal(q)
# main
for m in NaturalNumbers():
Pm = P(m)
for Pk in map(P, range(1, m+1)):
if isdoubleP( Pm - Pk) and isdoubleP( Pm + Pk):
print(Pk)
sys.exit(0)# 18 seconds