斐波那契数

来源:百度知道 编辑:UC知道 时间:2024/05/22 10:03:08
现在是用c++输入1000以上的数,算出1000以上的那个斐波那契数,这个程序是怎么样写的??
#include "stdafx.h"
#include <iostream>
using namespace std;
int Fibonacci(int N)
{
if(N <= 2)
return 1;
else
return Fibonacci(N - 1) + Fibonacci(N - 2);
}

int main()
{ int F;
cin>>F;
while (1<F&&F<1000)

{ F=0;
}
cout<<"输出错误,请重新输入"<<endl;

while (F>=1000)

cout<<Fibonacci(F)<<endl;

return 1;
}

我的程序是这样的。可是不可以运行哦,哪位大侠帮忙一下,谢谢了

搞不懂你到底在写什么。以下是最简单的写法:

#include "stdafx.h"
#include <iostream>
using namespace std;
int Fibonacci(int N)
{
if(N <= 2)return 1;
else{
int a=1,b=1,c=3,temp;
while(c<=N){
temp=a;
a=a+b;
b=temp;
c++;
}
return a;
}
}
int main()
{
int F;
cout<<"Enter the fibonacci number you want: ";
cin>>F;
cout<<Fibonacci(F)<<endl;
return 0;
}

你对Fibonacci()的定义没有什么问题,但是这个算法很没有效率,第1000个以上的项一分钟之内都算不出来,如果在300以内还好。

你的算法可能太慢了,Fibonacci(N) = Fibonacci(N - 1) + Fibonacci(N - 2),虽然看起来把一个问题Fibonacci(N)分成两个问题Fibonacci(N - 1)和Fibonacci(N - 2),但是两个子问题其实不是独立的。比如两个子问题都要计算Fibonacci(N - 3),就是说Fibonacci(N - 3)算了两遍。这样问题复杂度是指数级的。
有两种办法,一种就是在递归中保存已经计算过的子问题;另一种不用递归,用循环

我写一下大概循环的代码
int last=1,current=1;
for(;current<=1000;)
{
int tmp = current;
current += last;
last =tm