Daniele Fucini 3503357703
Add comments
Added comments to all the python solutions implemented so far.
2019-09-26 15:57:04 +02:00

47 lines
1.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/python3
# 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 are pentagonal and D = |Pk Pj| is minimised;
# what is the value of D?
from math import sqrt
from timeit import default_timer
from projecteuler import is_pentagonal
def main():
start = default_timer()
found = 0
n = 2
# Check all couples of pentagonal numbers until the right one
# is found. Use the function implemented in projecteuler.py to
# check if the sum and difference ot the two numbers is pentagonal.
while not found:
pn = n * (3 * n - 1) // 2
for m in range(1, n):
pm = m * (3 * m - 1) // 2
if is_pentagonal(pn+pm) and is_pentagonal(pn-pm):
found = 1
break
n = n + 1
end = default_timer()
print('Project Euler, Problem 44')
print('Answer: {}'.format(pn-pm))
print('Elapsed time: {:.9f} seconds'.format(end - start))
if __name__ == '__main__':
main()