48 lines
1.3 KiB
Python
48 lines
1.3 KiB
Python
'''
|
||
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?
|
||
'''
|
||
|
||
import math
|
||
|
||
def p(n):
|
||
return int(n * (3 * n - 1) / 2)
|
||
|
||
def isTriangle(n, triangleSet, triangleList):
|
||
if n > triangleList[-1]:
|
||
toBeat = triangleList[-1]
|
||
m = len(triangleList)
|
||
|
||
while toBeat < n:
|
||
m += 1
|
||
toBeat = p(m)
|
||
triangleList.append(toBeat)
|
||
triangleSet.add(toBeat)
|
||
|
||
return n == triangleList[-1]
|
||
|
||
else:
|
||
return n in triangleSet
|
||
|
||
def main():
|
||
print("Hello this is Patrick")
|
||
|
||
bestDif = math.inf
|
||
triangleList = [1, 5]
|
||
triangleSet = set(triangleList)
|
||
|
||
for i in range(2, 10000):
|
||
for j in range(1, i):
|
||
if isTriangle(p(i) - p(j), triangleSet, triangleList) and isTriangle(p(i) + p(j), triangleSet, triangleList):
|
||
bestDif = min(bestDif, abs(p(i) - p(j)))
|
||
|
||
print(bestDif)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main() |