欧拉计划 第12题 Highly divisible triangular number

题目

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

Let us list the factors of the first seven triangle numbers:

 1: 1
 3: 1,3
 6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?

三角数的序列是通过将自然数相加而生成的。 因此第7个三角数将是1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.前十个项将是:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

让我们列出前七个三角形数字的因数:

 1: 1
 3: 1,3
 6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

我们可以看到28是第一个具有超过5个除数的三角形。
具有超过500个除数的第一个三角形数的值是多少?

思路

c = a × b ,假设a ≤ 根号c,那么 b ≥ 根号c 。因数都是成对出现的,所以我们可以只需考虑从最小的因数到平方根为止的因数,将因数个数乘以2即可得到一个数字的因数个数。该题中,完全平方数的情况对此题没有影响,可以被忽略。

代码实现(python)

from past.builtins import xrange


def triangle(n):
    return (1 + n) * n / 2


if __name__ == '__main__':
    n = 2
    counter = 2
    while counter <= 500:
        n += 1
        counter = 2
        for i in xrange(2, int(pow(triangle(n), 1/2))+1, 1):
            if triangle(n) % i == 0:
                counter += 2
    print(triangle(n))

猜你喜欢

转载自blog.csdn.net/weixin_41297561/article/details/108635345