Skip to content

Commit

Permalink
(TheAlgorithms#8594) Optimization : avoid str
Browse files Browse the repository at this point in the history
Dividing number number and using remainder is about 25% faster.
  • Loading branch information
Bjiornulf committed Aug 31, 2023
1 parent b677a68 commit 078b2e9
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions project_euler/problem_034/sol1.py
Expand Up @@ -8,7 +8,7 @@

from math import factorial

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


def sum_of_digit_factorial(n: int) -> int:
Expand All @@ -19,7 +19,11 @@ def sum_of_digit_factorial(n: int) -> int:
>>> sum_of_digit_factorial(0)
1
"""
return sum(DIGIT_FACTORIAL[d] for d in str(n))
s = 0
while n != 0:
s += DIGIT_FACTORIAL[n % 10]
n //= 10
return s


def solution() -> int:
Expand Down

0 comments on commit 078b2e9

Please sign in to comment.