大家都知道斐波那契數列,現在要求輸入一個整數n,請你輸出斐波那契數列的第n項。 n<=39


// test14.cpp : 定義控制台應用程序的入口點。
//

#include "stdafx.h"
#include<iostream>
#include<string>
#include<cctype>
#include <vector>
#include<exception>
#include <initializer_list>
using namespace std;


class Solution {
public:
	int Fibonacci(int n) {
  //第一種方法 算法復雜度太高
	/*	if (n <= 2)
			return n - 1;
		else
			return Fibonacci(n - 1) + Fibonacci(n - 2);
		return 0;*/
		//第二種方法 節省空間,時間快
		int first = 0, second = 1,target=0;

		if (n < 2)
			return n ;
		for (int i = 0; i < n-1; i++)
		{
			target = first + second;
			first = second;
			second = target;
		}
		
		return target;
	}
};

int main()
{
	int num ;
	Solution so;
	while (cin>>num)
	{
		cout << "所求結果是: "  ;
		cout << so.Fibonacci(num) << endl;
		cout << endl;
	}
	
	return 0;
}
特別說明:數的位置:0 1 2 3 4 5 6  7  8  9 10 11.....
          對應的數:0 1 1 2 3 5 8 13 21 30 51 81...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM