又来水题解了。

模拟做法:

既然这题都给出了公式,那直接套上即可。

套的时候一定要注意括号的匹配。

AC代码

1
2
3
4
5
6
7
#include<bits/stdc++.h>
using namespace std;
double n;
int main(){
cin>>n;
printf("%.2lf",(pow((1+sqrt(5))/2,n)-pow((1-sqrt(5))/2,n))/sqrt(5));
}

递归做法:

此题正解肯定不是这样。

首先我们知道,斐波那契的公式是:

$f{1}=1,f{2}=1$

$f{n}(n>=3)= f{n-1}+f_{n-2}$

于是就有了递归。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<bits/stdc++.h>
using namespace std;
int n;
int fb(int x){
if(x==1||x==2)
return 1;
if(x==0)
return 0;
return fb(x-1)+fb(x-2);
}
int main(){
cin>>n;
cout<<fb(n)<<".00";
}

可这样会 TLE。

于是就要用记忆化。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<bits/stdc++.h>
using namespace std;
long long n,f[114]={0,1,1};//记忆化数组,要开long long
long long fb(int x){
if(x==0)
return 0;
if(!f[x])//没求过再求
f[x]=fb(x-1)+fb(x-2);
return f[x];
}
int main(){
cin>>n;
cout<<fb(n)<<".00";
}

就能非常顺利地通过了。

最后真神降临……

递推大法好!

每个OIer学递推应该第一个写的就是这个吧……

死去的记忆突然攻击我。

循环斐波那契数列的公式n次,最后输出第n项即为所求。

AC代码:

1
2
3
4
5
6
7
8
9
10
11
#include<bits/stdc++.h>
using namespace std;
long long n,f[114]={0,1,1};
int main(){
cin>>n;
for(int i=3;i<=n;i++){
f[i]=f[i-1]+f[i-2];//斐波那契数列的公式
}
cout<<f[n]<<".00";
return 0;
}

写的最长的一篇题解。

三种方法快肝死了