Java recursively calculates the number at the specified position of the Fibonacci sequence
1. Principle
Fibonacci sequence (Fibonacci sequence), also known as the golden section sequence, was introduced by the mathematician Leonardo Fibonacci (Leonardo Fibonacci) using rabbit breeding as an example, so it is also called "rabbit sequence". for:1、1、2、3、5、8、13、21、34……
Mathematically, this sequence is defined by the following recursive method: F(0)=1,F(1)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 2,n ∈ N*)
.
2. Code implementation
To calculate n
the number of the fibonacci series, we can use the following recursive function:
public class MyClass {
public static void main(String[] args){
int n = 10;
System.out.println("斐波那契数列第 " + n + " 个数为 " + Fibonacci(n));
}
//递归 n代表第几个数
public static int Fibonacci(int n) {
//前两个数为 1
//第三个数及后面的数为前面两数之和
//如果输入的 n 不合法将返回 -1
if (n == 1 || n == 2) {
return 1;
} else if (n > 2) {
return Fibonacci(n - 1) + Fibonacci(n - 2);
} else {
return -1;
}
}
}
time complexity:
- In the best case, when
n
is equal to1
or2
, return directly1
, and the time complexity isO(1)
. - In the worst case, when
n
is greater than2
, the function needs to be called recursivelyFibonacci()
to calculate the sum of the first two numbers, and the time complexity isO(2^n)
. Because each recursive call produces two subproblems, each subproblem produces two smaller subproblems, and so on, until the recursion reachesn
equal to1
or2
. - On average, so is the time complexity
O(2^n)
, since each number needs to be computed through recursive calls.
Space complexity:
- Since recursive calls save the local variables and return addresses of each call on the stack, the space complexity depends on the depth of recursion. In the worst case, the recursion depth is
n
, so the space complexity isO(n)
.
To sum up, the time complexity of the recursively implemented Fibonacci sequence function is exponential O(2^n)
, and the space complexity is linear O(n)
. Due to the exponential time complexity, the recursive implementation becomes very slow when computing larger Fibonacci numbers.
3. Running results
斐波那契数列第 10 个数为 55