斐波那契数列的第n项。

第一种:递归函数


  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #include<assert.h>
  4 
  5 int Fabonacci(int n)
  6 {
  7     if(n<=1&&n>=0)
  8     {
  9         return n;
 10     }
 11     return Fabonacci(n-1)+Fabonacci(n-2);
 12 }
 13 int main()
 14 {
 15     int n;
 16     printf("please input the value of n\n");
 17     scanf("%d",&n);
 18     printf("the result of %d is %d\n",n,Fabonacci(n));
 19     return 0;
 20 }

第二种:数组实现

创建一个两个元素的数组,初始化为1,求第n项的值,依次求出前面两项的和。

时间复杂度:O(n) 

空间复杂度:O(1)

  1 #include<stdio.h>
  2 int fib(int n)
  3 {
  4   int a[2]={1,1};
  5   int i=3;
  6   if(n<0)
  7   {
  8       return -1;
  9   }
 10   if(n==0)
 11   {
 12       return 0;
 13   }
 14   if(n<=2)
 15   {
 16       return a[n-1];
 17   }
 18   for(;i<=n;i++)
 19   {
 20       int tmp=a[0];
 21       a[0]=a[1];
 22       a[1]=a[0]+tmp;
 23   }
 24   return a[1];
 25 }
 26 int main()
 27 {
 28     int n=0;
 29     printf("please input the value of n\n");
 30     scanf("%d",&n);
 31     printf("the num is %d\n",fib(n));
 32     return 0;
 33 }

结果:
please input the value of n
0
the num is 0
[admin@localhost KEY]$ ./test
please input the value of n
5
the num is 5
[admin@localhost KEY]$ ./test
please input the value of n
4
the num is 3
[admin@localhost KEY]$ ./test
please input the value of n
-1
the num is -1

第三种:队列实现

思路同第二种

#include<iostream>
#include<queue>
using namespace std;
int fib(int n)
{
	if(n<0)
	{
		return -1;
	}
	if(n<=2)
	{
		return 1;
	}
	queue<int> q;
	q.push(1);
	q.push(1);
	for(int i=2;i<n;i++)
	{
		int tmp=q.front();
		q.pop();
		q.push(tmp+q.front());
	}
	q.pop();
	return q.front();
}
void test()
{
	int n1 =-1;
	int n2=2;
	int n3=5;
	cout<<fib(n1)<<endl;
    cout<<fib(n2)<<endl;
    cout<<fib(n3)<<endl;

}
int main()
{
	test();
	system("pause");
	return 0;
}

wKioL1crCJuznWfMAAAdrpDWKjY420.png


第四种:公式实现

int fib(int n)

{

if(n<0)

{

return -1;

}

 double gh5=sqrt((double)5);

 return (pow((1+gh5),n)-pow((1-gh5),n))/(pow((double)2,n)*gh5);

}

wKioL1crCJuznWfMAAAdrpDWKjY420.png

本文出自 “liveyoung” 博客,转载请与作者联系!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值