先上代码,你试试
package my.liu.qiuhe;
public class DiGuiQiuHe {
//求1!+2!+3!+.....+n!的和
public static void main(String[] args) {
//
用for循环
int n = 5;
int sum = useFor(n);
System.out.println(sum);
//
用递归算法
DiGuiQiuHe dg = new DiGuiQiuHe();
sum =0;
for(int i=1;i<=n;i++){
sum += dg.useDiGui(i);
}
System.out.println(sum);
}
public static int useFor(int n){
int sum = 0;
int m=1;
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
m*=j;
}
sum+=m;
m=1;
}
return sum;
}
public int useDiGui(int n){
int sum = 0;
sum = fn(n);
return sum;
}
private int fn(int n) {
if(n==1){return 1;}
else{
return fn(n-1)*n;
}
}
}