Project Euler 44

Project Euler 44

题目

Pentagon numbers

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, 7022=48, is not pentagonal.

Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference are pentagonal and D=|PkPj| is minimised; what is the value of D?

解决方案

先从小到大处理五边形数和值 s,再从小到大处理五边形数差值 d(d<s)

通过一个二元一次方程 a+b=s,ab=d 解出 a b 的值,如果 a b 也都是五边形数,那么可以输出所需值 d

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from itertools import count


# a+b=s,a-b=d,a-d=b
def solve():
p = []
st = set()
for s in (n * (3 * n - 1) // 2 for n in count(1)):
st.add(s)
for d in p:
if ((d ^ s) & 1) == 0:
a = (d + s) >> 1
if a in st and s - a in st:
return d
p.append(s)


print(solve())

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
Ujimatsu Chiya 微信 微信
Ujimatsu Chiya 支付宝 支付宝