-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem44.py
64 lines (47 loc) · 1.71 KB
/
problem44.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Project Euler Problem 44:
Pentagonal numbers are generated by the formula, P(n)=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 P(4) + P(7) = 22 + 70 = 92 = P8. However, their difference, 70 − 22 = 48, is not pentagonal.
Find the pair of pentagonal numbers, P(j) and P(k), for which their sum and difference are pentagonal and D = |P(k)
− P(j)| is minimised; what is the value of D?
"""
# P(n+1) - P(n) = 3n + 1
# Using this, generate adjacent differences, sum them, and check for the pentagonal properties
# Runs in ~6.5 minutes
from math import sqrt
from itertools import count
from collections import defaultdict
import sys
memoized = {}
def is_pentagonal(n):
# derived with the quadratic formula
if n not in memoized:
memoized[n] = sqrt(1 + 24*n) % 6 == 5
return memoized[n]
def generate_differences():
for n in count(2):
for i in range(n - 1, 0, -1):
# Formula for the sequence of first differences is D(n) = 3n + 1
yield tuple(map(lambda x: 3*x + 1, range(i, n)))
def find_lowest_diff():
lowest = 10**100
found_one = False
for differences in generate_differences():
lo_diff, hi_diff = differences[0], differences[-1]
diff = sum(differences)
if found_one and lo_diff == hi_diff:
# only 1 diff generated; final combo for this difference
return lowest
if not is_pentagonal(diff):
continue
lo = (lo_diff**2 - 3*lo_diff + 2) // 6
hi = (hi_diff**2 + 3*hi_diff + 2) // 6
if not is_pentagonal(lo + hi):
continue
found_one = True
if diff < lowest:
lowest = diff
print(find_lowest_diff())