✨ 新增欧拉第34、35题解法及说明
This commit is contained in:
67
solutions/0034/euler_34.py
Normal file
67
solutions/0034/euler_34.py
Normal file
@@ -0,0 +1,67 @@
|
||||
"""
|
||||
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
|
||||
|
||||
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
|
||||
|
||||
Note: As 1!=1 and 2!=2 are not sums they are not included.
|
||||
"""
|
||||
|
||||
import time
|
||||
from functools import lru_cache
|
||||
|
||||
|
||||
def timer(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
start_time = time.time()
|
||||
result = func(*args, **kwargs)
|
||||
end_time = time.time()
|
||||
print(f"{func.__name__} time: {end_time - start_time:.6f} seconds")
|
||||
return result
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def factorial(n: int) -> int:
|
||||
if n == 0:
|
||||
return 1
|
||||
elif n == 1:
|
||||
return 1
|
||||
elif n == 2:
|
||||
return 2
|
||||
elif n == 3:
|
||||
return 6
|
||||
elif n == 4:
|
||||
return 24
|
||||
elif n == 5:
|
||||
return 120
|
||||
elif n == 6:
|
||||
return 720
|
||||
elif n == 7:
|
||||
return 5040
|
||||
elif n == 8:
|
||||
return 40320
|
||||
elif n == 9:
|
||||
return 362880
|
||||
elif n == 10:
|
||||
return 3628800
|
||||
else:
|
||||
return n * factorial(n - 1)
|
||||
|
||||
|
||||
def sum_digits(n: int) -> int:
|
||||
tmp = str(n)
|
||||
return sum(factorial(int(digit)) for digit in tmp)
|
||||
|
||||
|
||||
@timer
|
||||
def main() -> None:
|
||||
res = list()
|
||||
for i in range(12, 9999999):
|
||||
if sum_digits(i) == i:
|
||||
res.append(i)
|
||||
print(sum(res))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user