Solution to problem 44
This commit is contained in:
parent
c3850f587f
commit
91b1f5c442
48
src/Python/Problem044.py
Normal file
48
src/Python/Problem044.py
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Created on 30 Aug 2021
|
||||||
|
|
||||||
|
@author: David Doblas Jiménez
|
||||||
|
@email: daviddoji@pm.me
|
||||||
|
|
||||||
|
Solution for problem 44 of Project Euler
|
||||||
|
https://projecteuler.net/problem=44
|
||||||
|
"""
|
||||||
|
|
||||||
|
from itertools import combinations
|
||||||
|
from operator import add, sub
|
||||||
|
from utils import timeit
|
||||||
|
|
||||||
|
def pentagonal(n):
|
||||||
|
return int(n*(3*n-1)/2)
|
||||||
|
|
||||||
|
@timeit("Problem 44")
|
||||||
|
def compute():
|
||||||
|
"""
|
||||||
|
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?
|
||||||
|
"""
|
||||||
|
dif = 0
|
||||||
|
pentagonal_list = set(pentagonal(n) for n in range(1,2500))
|
||||||
|
pairs = combinations(pentagonal_list, 2)
|
||||||
|
for p in pairs:
|
||||||
|
if add(*p) in pentagonal_list and abs(sub(*p)) in pentagonal_list:
|
||||||
|
dif = (abs(sub(*p)))
|
||||||
|
# the first one found would be the smallest
|
||||||
|
break
|
||||||
|
|
||||||
|
return dif
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
|
||||||
|
print(f"Result for Problem 44: {compute()}")
|
Loading…
x
Reference in New Issue
Block a user