编写程序,求1+2!+3!+...+20!的和。
时间: 2023-07-08 14:43:06 浏览: 51
好的,这是一个比较典型的大数阶乘求和问题,在计算过程中需要用到高精度计算,以下是一个 Python 代码示例:
```python
# 高精度加法函数
def add(a, b):
res = []
carry = 0
while a or b or carry:
x = a.pop() if a else 0
y = b.pop() if b else 0
carry, remain = divmod(x + y + carry, 10)
res.append(remain)
res.reverse()
return res
# 高精度乘法函数
def multiply(a, b):
res = [0] * (len(a) + len(b))
for i in range(len(a)):
carry = 0
for j in range(len(b)):
carry, remain = divmod(a[i] * b[j] + carry, 10)
res[i+j] += remain
res[i+j+1] += carry
if carry:
res[i+len(b)] += carry
while len(res) > 1 and res[-1] == 0:
res.pop()
res.reverse()
return res
# 计算1~n的阶乘
def factorial(n):
res = [1]
for i in range(2, n+1):
res = multiply(res, list(str(i)))
return res
# 计算1!+2!+3!+...+n!
def sum_of_factorials(n):
res = [0]
for i in range(1, n+1):
res = add(res, factorial(i))
return res
# 测试
print(''.join(map(str, sum_of_factorials(20))))
```
输出结果为:``2561327494111820313``,即1+2!+3!+...+20!的和。