Skip to content

Commit 078b2e9

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

File tree

1 file changed

+6
-2
lines changed

1 file changed

+6
-2
lines changed

Diff for: project_euler/problem_034/sol1.py

+6-2
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:

0 commit comments

Comments
 (0)