1!+2!+…n!
思路1,递归
n的阶乘 = n乘以 n-1 的阶乘
n! = nx(n-1)!
/**
* n! 等于 n*(n-1)!
*/
public static int factorial(int n){
int a = 1;
if(n==1){
a =1;
}
if(n>1){
a= n*factorial(n-1);
}
return a;
}
思路2,for循环
n! = 1x2x…xn
/**
* n! = 1*2* ... *n
*/
public static int njie2(int n){
int a =1;
for (int i = 1; i <=n ; i++) {
a= a*i;
}
return a;
}
整体代码
public class JieCheng {
public static void main(String[] args) {
int sum = 0;
int n = 10;
for (int i = 1; i <= n; i++) {
sum+= factorial(i);
}
System.out.println(sum);
}
/**
* n! 等于 n*(n-1)!
*/
public static int factorial(int n){
int a = 1;
if(n==1){
a =1;
}
if(n>1){
a= n*factorial(n-1);
}
return a;
}
/**
* n! = 1*2* ... *n
*/
public static int factorial2(int n){
int a =1;
for (int i = 1; i <=n ; i++) {
a= a*i;
}
return a;
}
}