用java求1+2!+3!+…+20!
时间: 2023-12-16 12:06:20 浏览: 72
以下是两种Java求1+2!+3!+...+20!的例子:
1.使用for循环和嵌套循环计算阶乘和
```java
public class Test{
public static void main(String[] args){
System.out.println("1!2!+3!+……+20!=" + getSum(20));
}
public static long getSum(int n){
int i, k, fac, sum = 0;
for(i = 1; i <= n; i++){
fac = 1;
for(k = 1; k <= i; k++){
fac = fac * k;
}
sum = sum + fac;
}
return sum;
}
}
```
2.使用递归函数计算阶乘和
```java
public class Prog21{
public static void main(String[] args){
long sum = 0;
for(int i = 0; i < 20; i++){
sum += factorial(i + 1);
}
System.out.println(sum);
}
//阶乘
private static long factorial(int n){
if(n == 1){
return 1; }
return n * factorial(n - 1);
}
}
```
阅读全文