求1!+2!+3!+4!+……+n! n=20
时间: 2023-11-24 09:51:54 浏览: 128
以下是Java和C语言两种实现方法:
Java代码实现:
```java
import java.math.BigInteger;
public class FactorialSum {
public static void main(String[] args) {
int n = 20;
BigInteger sum = BigInteger.ZERO;
BigInteger factorial = BigInteger.ONE;
for (int i = 1; i <= n; i++) {
factorial = factorial.multiply(BigInteger.valueOf(i));
sum = sum.add(factorial);
}
System.out.println(sum);
}
}
```
C语言代码实现:
```c
#include <stdio.h>
long long factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
long long fun(int n) {
long long sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial(i);
}
return sum;
}
int main() {
int n = 20;
printf("%lld", fun(n));
return 0;
}
```
阅读全文