Definition and optimization of Fibonacci sequence

In mathematics , the fee Fibonacci series is based on a recursive method to define:

  • F_{0}=0
  • F_{1}=1
  • F_{n}=F_{​{n-1}}+F_{​{n-2}}(n≧2)

Principles and limitations of recursive algorithms: 

Recursion: https://blog.csdn.net/qq_40479037/article/details/87601397

 On the code:

# include<iostream>
# include<algorithm>
const int MAX_N = 10000;

using namespace std;

//斐波拉切数列定义
unsigned long long fib0(int n){
	//时间复杂度来源于要重复计算 
	if(n <= 1)
		return n;
	return fib0(n-1)+fib0(n-2);
} 

//记忆搜索 
unsigned long long memo[MAX_N+1]; 
int fib1(int n){//最多算到46,实质上还是指数阶
	
	if(n <= 1)	return n;//前两项
	//此时有未计算和已经计算好存储到数组中的两种情况
	//因为等于0的情况在斐波拉切数列中只有第一项 
	if(memo[n] != 0) return memo[n]; 
	return memo[n] = fib1(n-1)+fib1(n-2);
}

//指数阶化函数阶 
long long fib2(int n){
	if(n <= 1)
		return 1;
	long long first = 0,second = 1,third = 0;
	for(int i = 2;i <= n;++i)
	{
		third = first + second;
		first = second;
		second = third;
	 } 
	 return third;
}

int main()
{
	int n;
	cin >> n;
	cout << "fib1:" << fib1(n) << endl;
	cout << "fib2:" << fib2(n) << endl;
	cout << "fib0:";
	cout << fib0(n) << endl;
	
 return 0;
}

Run it and you will find that fib0 is much longer than the previous two

Compared with the fib1 function, its redundant time comes from repeated calculations

For the fib2 function, its time is wasted on the algorithm itself

If you compare fib1 and fib2 , you will find that fib2 has better performance, because fib1 is still not out of the recursive call 

 

Guess you like

Origin blog.csdn.net/qq_40479037/article/details/87518265