5.5递归
程序调用自身的编程技巧成为递归
计算斐波那契数列
求任意一项对应的斐波那契数列的值。
1,1,2,3,5,8,13,21......
public static long feibo(int n){
long num1 = 1;
long num2 = 1;
long cur = num1+num2;
for(int i = 4;i<=n;i++){
num1 = num2;
num2 = cur;
cur = num1+num2;
}
return cur;
}
- 递归的优势
- 编写简单
- 数据结构而言;树,堆这样的结构使用递归特别简单
- 劣势
- 耗内存
- 时间成本高
import java.util.Scanner;
public class test {
public static void main(String[] args) {
/**
* 求阶乘
*/
//输入一个数
Scanner scanner=new Scanner(System.in);
int getin = scanner.nextInt();
int factorial = Factorial(getin,1);
System.out.println(factorial);
}
public static int Factorial(int getin,int num){
if (getin>1){
num=num*getin;
return Factorial(getin-1,num);
}else {
return num;
}
}
}