Project Euler Question 12 Highly divisible triangular number

topic

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?

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

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

Let us list the factors of the first seven triangular 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 with more than 5 divisors.
What is the value of the first triangular number with more than 500 divisors?

Ideas

c = a × b, assuming a ≤ radical c, then b ≥ radical c. Factors appear in pairs, so we can only consider the factors from the smallest factor to the square root, and multiply the number of factors by 2 to get the number of factors of a number. In this question, the situation of the perfect square number has no effect on this question and can be ignored.

Code implementation (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))

 

Guess you like

Origin blog.csdn.net/weixin_41297561/article/details/108635345