The beauty of programming: 2.9 Fibonacci series, 2.9 Fibonacci
The Fibonacci series is a classic example of recursion when we are learning the C language. Of course, there will also be an example of the tower of legends.
This problem is defined as follows:
0 (x <= 0)
F (x) = 1 (x = 1)
F (x-1) + f (x-2) (x> 1)
After seeing this recursive formula, we can easily write the following code:
Function declaration:
typedef long long ll;
ll DutFibonacci_1(int);
Function Definition:
/* Recursive solution of the classic Fibonacci series, and everyone knows that this method is very inefficient */ll DutFibonacci_1 (int n) {if (n <= 0) return 0; else if (n = 1) return 1; elsereturn DutFibonacci_1 (n-1) + DutFibonacci_1 (n-2 );}
However, when you enter a large x value, you will find that you have waited for a long time and still have no output. This is the problem of low recursion efficiency. Recursion is to use the stack idea, calculate the previous value of the stack again and again, and then calculate the next value of the stack again and again. Finally, obtain the final value (the last value ). Therefore, we can know that a series of operations, such as the address of the function and the value of each parameter, need to be saved here, are definitely a waste of time and resources. Therefore, we need to find another way to solve this problem.
Most recursive problems can be solved through loops. Therefore, we can try to write the following circular code:
Function declaration:
ll DutFibonacci_2(int);
Function Definition:
Ll DutFibonacci_2 (int n) {if (n <= 0) return 0; else if (n = 1) return 1; ll one = 1; ll two = 0; ll result = 0;/* The non-recursive solution is also very simple. You can use two intermediate numbers to calculate the value that "used to exist" */for (int I = 2; I <= n; ++ I) {result = one + two; two = one; one = result;} return result ;}