Skip to content

Fixes: #3869: Optimize solution #2 for Euler's Problem #74 #3872

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 16 additions & 9 deletions project_euler/problem_074/sol2.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@
"""


def factorial(a: int) -> int:
"""Returns the factorial of the input a
def factorial(a: int, factorial_cache: dict = {}) -> int:
"""Returns the factorial of the input a and a cache of factorials
of single digits (optionals)
>>> factorial(5)
120

Expand All @@ -31,23 +32,27 @@ def factorial(a: int) -> int:
>>> factorial(0)
1
"""

# The factorial function is not defined for negative numbers
if a < 0:
raise ValueError("Invalid negative input!", a)

# The case of 0! is handled separately
if a == 0:
return 1
temporary_computation = 1
else:
# use a temporary support variable to store the computation
temporary_computation = 1
temporary_number = a
while temporary_number > 0:
temporary_computation *= temporary_number
temporary_number -= 1

while a > 0:
temporary_computation *= a
a -= 1
# save the factorial value, for future reference for the same number
# in factorial_sum, e.g., 6666
if a < 10:
factorial_cache[a] = temporary_computation

return temporary_computation
return temporary_computation, factorial_cache


def factorial_sum(a: int) -> int:
Expand All @@ -65,8 +70,10 @@ def factorial_sum(a: int) -> int:
convert the digit back into an int
and add its factorial to fact_sum.
"""
factorial_cache = {}
for i in str(a):
fact_sum += factorial(int(i))
factorial_value, factorial_cache = factorial(int(i), factorial_cache)
fact_sum += factorial_value

return fact_sum

Expand Down