Problem 44 Pentagon numbers

2016-11-03 13:54:00   技术   python projecteulor

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?

我承认这题我不是独立思考的,看了下别人的代码

我自己的代码企图把所有(所有的范围多大?)的五边形数字进行排列组合,然后再找出结果来,结果又慢又占空间

不过算b平方-4ac是我自己想到的

五边形数字到底是什么我还是去维基了一下,之前还真不知道

import math


def is_pentagon(number):
    return (math.sqrt(24 * number + 1) + 1) % 6 == 0


def cal_pentagon(n):
    return n * (3 * n - 1) / 2

j_n = 2
while True:
    j = cal_pentagon(j_n)
    for i_n in reversed(range(1, j_n)):
        i = cal_pentagon(i_n)
        if is_pentagon(j - i) and is_pentagon(i + j):
            print j - i, i, j, i + j
            exit(0)
    j_n += 1
评论已关闭。
评论共