Java编程1!+2!+3!+...+n!的和要用递归,请写详细点

实现输入一个正整数,计算并输出1!+2!+3!+...+n!的和,用递归
2024-12-04 04:29:21
推荐回答(2个)
回答1:

//递归阶乘
static long mul(int num){
long mul=1l;

if(num==1) //num等于1 还回,否则调用自己迭代
mul = 1l*mul;
else
mul= num*mul(num-1);
return mul;
}
//循环求和
static long sum(int num){
long sum=0l;
for(int i=1;i<=num;i++)
sum+=mul(num);
return sum;
}
public static void main(String[] args) {

System.out.println(sum(3));
}

回答2:

如下,要计算5的话。。

public class Dog {

public static void main(String args[]) {

Dog dog = new Dog();
int number = 5;

dog.calcSum(5);

}

private long calcSum(int number){
long sum = 0L;

for(int i = 1; i <= number; i++){
sum += calcFac(i);
}

return sum;
}

private long calcFac(int num){

if(num == 1){
return 1;
}else{
return num*calcFac(num-1);
}

}
}