一、斐波那契数列(Fibonacci sequence),又称黄金分割数列,这个数列最早是由印度数学家提出来的。
该序列的前几项是这样的:0,1,1,2,3,5,8,13,21,34,⋯
在数学上,斐波纳契数列以如下被以递归的方法定义:
F(0)=0
F(1)=1
F(n)=F(n−1)+F(n−2) ,(n≥2,n∈N)
Fibonacci 数列的通项公式:F(n)=F(n−1)+F(n−2)
二、递归思想
(一)定义:一个直接调用自己或者通过一系列的调用语句间接地调用自己的函数叫做递归函数。
package linear_list;
/**
* Recursion.
*
* @author 前夜
*
*/
public class Recursion {
/**
********************
* Sum to N.
*
* @param paraN The given paraN.
* @return Return the sum.
********************
*/
public static int sumToN(int paraN) {
if (paraN < 0) {
return 0;
} // Of if
return sumToN(paraN - 1) + paraN;
}// Of sumToN
/**
********************
* Fibonacci sequence.
*
* @param paraN
* @return
********************
*/
public static int fibonacci(int paraN) {
if (paraN < 0) {
return 0;
} // Of if
else if (paraN == 1) {
return 1;
} // Of if
else
return fibonacci(paraN - 1) + fibonacci(paraN - 2);
}// Of fibonacci
/**
********************
* The entrance of the program.
*
* @param args
********************
*/
public static void main(String args[]) {
int tempValue = 5;
System.out.println("The sum of 0 to " + tempValue + " is " + sumToN(tempValue));
tempValue = -5;
System.out.println("The sum of 0 to " + tempValue + " is " + sumToN(tempValue));
for (int i = 0; i < 10; i++) {
System.out.println("Fibonacci " + i + ": " + fibonacci(i));
} // Of for i
}// Of main
}// Of class Recursion
输出结果:
The sum of 0 to 5 is 15
The sum of 0 to -5 is 0
Fibonacci 0: 0
Fibonacci 1: 1
Fibonacci 2: 1
Fibonacci 3: 2
Fibonacci 4: 3
Fibonacci 5: 5
Fibonacci 6: 8
Fibonacci 7: 13
Fibonacci 8: 21
Fibonacci 9: 34