分享一个刷题时候遇到的有意思的答案

 原题要求计算斐波那契数列 某一项的值。

 ① 第一种是递归,这个大家都应该知道(有空我再补充)

 ② 看到网友 给出了一种巧妙的解法,最直接的区别是 只需要定义两个变量即可 实现求解,算法复杂度分析我有空再补充。

// test.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
using namespace std;

int Fibonacci(int n);


int main()
{
	cout<<Fibonacci(15);
	system("pause");
    return 0;
}


int Fibonacci(int n) 
{
	int f = 0, g = 1;
	while (n--)
	{
		cout << "f=" << f << "\t";
		cout << "g=" << g << "\n";
		g += f;
		f = g - f;
	}
	return g;
}

结果:

猜你喜欢

转载自blog.csdn.net/zhangxz259/article/details/81383129