solutions of problem 21 and problem 20
This commit is contained in:
67
solutions/0020.FactorialDigitSum/euler_20.py
Normal file
67
solutions/0020.FactorialDigitSum/euler_20.py
Normal file
@@ -0,0 +1,67 @@
|
||||
"""
|
||||
n! means `n! = n × (n-1) × ... 2 × 1`.
|
||||
For example, 10! = 10 × 9 × ... × 2 × 1 = 3628800,
|
||||
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27 .
|
||||
|
||||
Find the sum of the digits in the number 100!.
|
||||
"""
|
||||
|
||||
import math
|
||||
import time
|
||||
from functools import reduce
|
||||
|
||||
|
||||
def timer(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
start_time = time.time()
|
||||
result = func(*args, **kwargs)
|
||||
end_time = time.time()
|
||||
print(f"Execution time: {end_time - start_time:.8f} seconds")
|
||||
return result
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
def large_multiplication(a: str, b: str) -> str:
|
||||
result = [0] * (len(a) + len(b))
|
||||
for i in range(len(a) - 1, -1, -1):
|
||||
carry = 0
|
||||
for j in range(len(b) - 1, -1, -1):
|
||||
product = int(a[i]) * int(b[j]) + result[i + j + 1] + carry
|
||||
result[i + j + 1] = product % 10
|
||||
carry = product // 10
|
||||
result[i] += carry
|
||||
return "".join(map(str, result)).lstrip("0") or "0"
|
||||
|
||||
|
||||
def factorial(n: int) -> int:
|
||||
res = reduce(lambda x, y: x * y, range(1, n + 1))
|
||||
return res
|
||||
|
||||
|
||||
@timer
|
||||
def factorial_digit_sum(n: int) -> int:
|
||||
if n >= 1000:
|
||||
fact = math.factorial(n)
|
||||
else:
|
||||
fact = factorial(n)
|
||||
return sum(int(digit) for digit in str(fact))
|
||||
|
||||
|
||||
@timer
|
||||
def large_factorial(n: int) -> int:
|
||||
result = "1"
|
||||
for i in range(2, n + 1):
|
||||
result = large_multiplication(result, str(i))
|
||||
print(f"{n}!={result}")
|
||||
sum_all = sum(int(digit) for digit in result)
|
||||
return sum_all
|
||||
|
||||
|
||||
def main():
|
||||
print(factorial_digit_sum(100))
|
||||
print(large_factorial(100))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user