C++ 实现斐波那契数列和递归寻找+高效寻找

/*
*Definition:
*Author:
*Date:
*/
#include <iostream>
#include <array>
#include<vector>
using namespace std;

class Fibo{
    
    
	int m_num=0;
	const int m_firstNum = 0;
	const int m_secondNum = 1;
	vector<int>m_fib;
public:
	Fibo(){
    
    }
	Fibo(int n) :m_num(n)
	{
    
    
		int temp1 = m_firstNum;
		m_fib.push_back(temp1);
		int temp2 = m_secondNum;
		m_fib.push_back(temp2);
		int sum;
		for (int i = 2; i < n; i++)
		{
    
    
			sum = temp1 + temp2;
			m_fib.push_back(sum);
		}
	}
	//高效法,复杂度为N
	int getFibo(int &num){
    
    
		if (num == 0){
    
    
			return 0;
		}
		else if (num == 1)
		{
    
    
			return 1;
		}
		else if (num > 1)
		{
    
    
			int sum;
			int Ftemp = m_firstNum;
			int Stemp = m_secondNum;
			for (int i = 0; i < num - 2; i++)
			{
    
    
				sum = Ftemp + Stemp;
				Ftemp = Stemp;
				Stemp = sum;
			}
			return sum;
		}
		else
		{
    
    
			cout << "Please input the right positive number." << endl;
		}
	}
	//递归法,复杂度为2ˇn,效率慢
	int getFiboDigui(int &num)
	{
    
    
	if (num<2)
		{
    
    
			cout << "Please input the number bigger than 2" << endl;
			return 0;
		}
		int Finnum;
		Finnum = this->m_fib[num - 2] + this->m_fib[num - 1];
		return Finnum;
		
		
	}
};

	int main()
	{
    
    
		Fibo f;
		Fibo f2(5);
		int pos;
		cout << "Input the position you want to know: " << endl;
		cin >> pos;

		cout << "The number:" << f.getFibo(pos) << endl;

		cout << "The 2number:" << f2.getFiboDigui(pos) << endl;
		system("PAUSE");
		return 0;
	}

递归法时间复杂度为
递归

高效:
高效

猜你喜欢

转载自blog.csdn.net/guanxunmeng8928/article/details/107465657