递归:阶乘、斐波那契数列
- 阶乘
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static void main(String[] args) { System.out.println(factorial(5));; } //factorial 阶乘 public static long factorial(int n) { if (n == 1) { return 1; } return n*factorial(n-1); }
- 阶乘画图理解
- 斐波那契数列递归实现:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static void main(String[] args) { System.out.println(Fibonacci(15)); } //Fibonacci 斐波那契数列 public static long Fibonacci(int n) { if (n == 1 || n == 2) { return 1; } return Fibonacci(n-1)+Fibonacci(n-2); }
- 斐波那契数列循环实现:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public static void main(String[] args) { System.out.println(Fibonacci(40)); } //Fibonacci 斐波那契数列 public static long Fibonacci(int index) { if (index == 1 || index == 2) { return 1; } long first = 1, second = 1, result = 0; for (int i=3; i<index+1; i++) { result = first + second ; first = second; second = result; } return result; }
- 画图理解斐波那契数列: