递归的方式计算阶乘

public class Demo1 {
//一列数的规则如下: 1、1、2、3、5、8、13、21、34…… 求第n位数是多少, 用递归算法实现
public static void main(String[] args) {
System.out.println(jiecheng(5)); // 5的阶乘(通过阶乘体验一下递归算法)
set(8); //使用for循环求出第n位数
System.out.println(foo(8));  //使用递归求出第n位数
}

public static int jiecheng(int a) {// 阶乘递归
if (a == 1) {
return 1;//方法的出口,避免死循环
} else {
return a * jiecheng(a - 1);
}
}

public static void set(int s) {//使用for循环求出第n位数
int a = 1;
int b = 1;
int c = 0;
for (int i = 2; i < s; i++) {
c = b;
b = a + b;
a = c;
System.out.print(b + " ");
}
}

public static int foo(int i) {//使用递归求出第n位数
if (i <= 0) {
return 0;
} else if (i > 0 && i <= 2)
return 1;
return foo(i - 1) + foo(i - 2);//??
}

}

猜你喜欢

转载自www.cnblogs.com/sunda847882651/p/9416443.html