我为Project Euler #12编写了这段代码。它非常慢(或不起作用),我发现另一个非常相似的代码并立即得到答案。我的代码:
import math
def get_triangular(nth):
return sum(range(1,nth+1))
def get_divisors_count(n):
divisors = 0
for a in range(1,math.ceil(n/2)+1):
if n%a == 0:
divisors += 1
return divisors
a = 1
while(True):
if get_divisors_count(get_triangular(a)) > 500:
print(a)
a += 1
我在 Stack Overflow 上找到的代码:
import math
def main():
l = []
one = 0
a = 1
b = 2
while one == 0:
a = a + b
b += 1
l = []
sqrt_a = int(math.sqrt(a))
for x in range(1, sqrt_a + 1):
if a % x == 0:
l.append(x)
if x < math.sqrt(a):
l.append(a // x)
if len(l) > 500:
# print(a)
one = 1
print(a, b, len(l))
if __name__ == '__main__':
main()