Skip to content

Commit 1ad4d05

Browse files
committed
Improve solution
1 parent 94f38dd commit 1ad4d05

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

project_euler/problem_012/sol1.py

+11-8
Original file line numberDiff line numberDiff line change
@@ -21,17 +21,20 @@
2121
What is the value of the first triangle number to have over five hundred
2222
divisors?
2323
"""
24-
from math import sqrt
2524

2625

2726
def count_divisors(n):
28-
nDivisors = 0
29-
for i in range(1, int(sqrt(n)) + 1):
30-
if n % i == 0:
31-
nDivisors += 2
32-
# check if n is perfect square
33-
if n ** 0.5 == int(n ** 0.5):
34-
nDivisors -= 1
27+
nDivisors = 1
28+
i = 2
29+
while i * i <= n:
30+
multiplicity = 0
31+
while n % i == 0:
32+
n //= i
33+
multiplicity += 1
34+
nDivisors *= multiplicity + 1
35+
i += 1
36+
if n > 1:
37+
nDivisors *= 2
3538
return nDivisors
3639

3740

0 commit comments

Comments
 (0)