递归有两种表示:
直接调用和间接调用;
利用阶乘递归遍历求阶乘和:
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 4; i++){
sum += new DiGuiPractise2().factorial(i);
}
System.out.println(sum);
}
long multiply ;
public long factorial(int n){
if(n == 1){
return 1;
}
multiply = n*factorial(n-1);
return multiply;
}
利用递归求阶乘和:
public static void main(String[] args) {
System.out.println(new DiGuiPractise2().factorail(4));
}
long multiply ;
public long factorial(int n){
if(n == 1){
return 1;
}
multiply = n*factorial(n-1);
return multiply;
}
long sum = 0;
public long factorail(int n){
if(n == 1){
return 1;
}
sum = factorial(n) + factorail(n-1);
return sum;
}
|