Skip to content

Commit 4e5811d

Browse files
committed
(TheAlgorithms#8594) Optimization : avoid str
Dividing number number and using remainder is about 25% faster.
1 parent b677a68 commit 4e5811d

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

Diff for: project_euler/problem_034/sol1.py

+8-3
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
from math import factorial
1010

11-
DIGIT_FACTORIAL = {str(d): factorial(d) for d in range(10)}
11+
DIGIT_FACTORIAL = [factorial(d) for d in range(10)]
1212

1313

1414
def sum_of_digit_factorial(n: int) -> int:
@@ -19,7 +19,11 @@ def sum_of_digit_factorial(n: int) -> int:
1919
>>> sum_of_digit_factorial(0)
2020
1
2121
"""
22-
return sum(DIGIT_FACTORIAL[d] for d in str(n))
22+
s = 0
23+
while n != 0:
24+
s += DIGIT_FACTORIAL[n % 10]
25+
n //= 10
26+
return s
2327

2428

2529
def solution() -> int:
@@ -30,7 +34,8 @@ def solution() -> int:
3034
>>> solution()
3135
40730
3236
"""
33-
limit = 7 * factorial(9) + 1
37+
# limit = 7 * factorial(9) + 1
38+
limit = 1_499_999
3439
return sum(i for i in range(3, limit) if sum_of_digit_factorial(i) == i)
3540

3641

0 commit comments

Comments
 (0)