Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 71ba3a1

Browse files
authoredNov 1, 2021
Improve Project Euler problem 012 solution 1 (TheAlgorithms#5731)
* Improve solution * Uncomment code that has been commented due to slow execution affecting Travis * Retest
1 parent 06ab650 commit 71ba3a1

File tree

1 file changed

+13
-11
lines changed

1 file changed

+13
-11
lines changed
 

‎project_euler/problem_012/sol1.py

+13-11
Original file line numberDiff line numberDiff line change
@@ -21,27 +21,29 @@
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

3841
def solution():
3942
"""Returns the value of the first triangle number to have over five hundred
4043
divisors.
4144
42-
# The code below has been commented due to slow execution affecting Travis.
43-
# >>> solution()
44-
# 76576500
45+
>>> solution()
46+
76576500
4547
"""
4648
tNum = 1
4749
i = 1

0 commit comments

Comments
 (0)
Please sign in to comment.