1147: 零起点学算法54——Fibonacci

小鱼儿 2023-01-11 08:44 244阅读 0赞

Description

Fibonacci数列定义为(1,1,2,3,5,8,…..),即每个元素是前两个元素的和。如果一个Fibonacci数与所有小于它的Fibonacci数互质,那么称之为Fibonacci质数。
现在要求你输出前n个Fibonacci数
The Fibonacci Numbers {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 …} are defined by the recurrence:
F(0)=0
F(1)=1
F(i)=F(i-1)+F(i-2)
Write a program to calculate the Fibonacci Numbers.

Input

The first line of the input file contains a single integer T, the number of test cases. The following T lines,each contains an integer n ( 0 <= n <= 45 ), and you are expected to calculate Fn

Output

Output Fn on a separate line.

" class="reference-link">Sample Input 5f8f312f51791b8bb0ed0ae07c2ffa43.gif

  1. 5
  2. 0
  3. 3
  4. 5
  5. 9
  6. 20

Sample Output

  1. 0
  2. 2
  3. 5
  4. 34
  5. 6765

Source

零起点学算法

Code

  1. #include<stdio.h>
  2. #include<iostream>
  3. using namespace std;
  4. ///F(0)=0,F(1)=1,F(n)=F(n-1)+F(n-2)(n≥2,n∈N*)
  5. int Fibonacc(int n)
  6. {
  7. if(n==0)
  8. return 0;
  9. else if(n==1)
  10. return 1;
  11. else
  12. return Fibonacc(n-1)+Fibonacc(n-2);
  13. }
  14. int main()
  15. {
  16. int T;
  17. cin>>T;
  18. while(T--)
  19. {
  20. int n;
  21. cin>>n;
  22. cout<<Fibonacc(n)<<endl;
  23. }
  24. }

第一遍代码如图,结果显示超时。题目要求n最大为45,算出最终结果耗时14s.本题我使用的是递归,时间复杂度较高,因此会有超时问题。在网上搜索其他人的代码,发现使用数组存储会比较好。

  1. #include<stdio.h>
  2. #include<iostream>
  3. using namespace std;
  4. ///F(0)=0,F(1)=1,F(n)=F(n-1)+F(n-2)(n≥2,n∈N*)
  5. int main()
  6. {
  7. int T;
  8. cin>>T;
  9. while(T--)
  10. {
  11. int n;
  12. int a[50]={0,1};
  13. cin>>n;
  14. for(int i=2;i<=n;i++)
  15. {
  16. a[i]=a[i-1]+a[i-2];
  17. }
  18. cout<<a[n]<<endl;
  19. }
  20. }

在最后一个循环的地方除了点错,一开始循环的条件是i<n,结果发现每次输出的a[n]都是0.后来发现是下标的问题,所以把循环的条件改成了i<=n;

发表评论

表情:
评论列表 (有 0 条评论,244人围观)

还没有评论,来说两句吧...

相关阅读