Triangle number is ones composed by adding previous number together, like the additive analog of factorial number: Tn = 1 + 2 + 3 + ... + n. Now it asks what is the first triangle number with more than 500 divisors?
There are several ways to generate a triangle number. One is use the plain equation to sum up; other one is clearly use the sum-up equation Tn = n*(n-1)/2. However, since what we basically need here is to iterate all triangle numbers starts with 1 (or some bigger yet still small number), I add a step every time using Tn = Tn-1 + n. I think latter two should be mostly at the same speed.
Another thing is to find the number of divisors for a number. This is just iterate from 1 to sqrt(n), according to many math properties. Also since divisors appear in pairs, one might add two every time it finds a fit one if one uses this method; but minus one if the divisor it finds happens to be the sqrt(n).
Codes:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from math import sqrt, floor | |
def euler12(): | |
D = 0 | |
n = 1 | |
step = 2 | |
while D < 500: | |
n += step | |
step += 1 | |
D = findDivisor(n) | |
return n | |
def findDivisor(m): | |
d = 2 | |
for i in range(2,int(floor(sqrt(m)))): | |
if m%i == 0: | |
d += 2 | |
if m/i == i: | |
d -= 1 | |
return d | |
if __name__ == '__main__': | |
print euler12() |
No comments:
Post a Comment