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 4e5811d
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 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 All @@ -30,7 +34,8 @@ def solution() -> int:
>>> solution()
40730
"""
limit = 7 * factorial(9) + 1
# limit = 7 * factorial(9) + 1
limit = 1_499_999
return sum(i for i in range(3, limit) if sum_of_digit_factorial(i) == i)


Expand Down

0 comments on commit 4e5811d

Please sign in to comment.