斐波那契数列代码实现优化

1、斐波那契数列介绍:https://zhuanlan.zhihu.com/p/26752744

2、代码实现:

【1.0】递归实现(无优化):

#include <bits/stdc++.h>
  using namespace std;
int n;
long long s;
long long count(int t)
{
	if (t<=0) return 0;
	else if (t==1) return 1;
	else return count(t-1)+count(t-2);
}
int main()
{
	scanf("%d",&n);
	s=count(n);
	printf("%lld",s);
	return 0;
}

递归计算缺点:每一项会被计算两次,因此,可以用数组储存计算结果。

【2.0】循环实现数组储存结果(时间复杂度优化)

#include <bits/stdc++.h>
  using namespace std;
int n,i;
long long s[105];
int main()
{
	s[1]=1;
	s[2]=1;
	scanf("%d",&n);
	for (i=3;i<=n;i++)
	{
		s[i]=s[i-1]+s[i-2];
	}
	printf("%lld\n",s[n]);
	return 0;
}

【2.1】循环实现数组取模储存结果(空间复杂度优化)

#include <bits/stdc++.h>
  using namespace std;
int n,i;
long long s[3];
int main()
{
	s[1]=1;
	s[2]=1;
	s[0]=2;
	scanf("%d",&n);
	for (i=4;i<=n;i++)
	{
		s[i%3]=s[(i-1)%3]+s[(i-2)%3];
	}
	printf("%lld\n",s[n%3]);
	return 0;
}

【2.2】循环实现数组位运算储存结果

#include <bits/stdc++.h>
  using namespace std;
int n,i;
long long s[2];
int main()
{
	s[1]=1;
	s[0]=0;
	scanf("%d",&n);
	for (i=2;i<=n;i++)
	{
		s[i&1]+=s[!(i&1)];
	}
	printf("%lld\n",s[n&1]);
	return 0;
}

【3.0】迭代

#include <bits/stdc++.h>
  using namespace std;
int n;
long long x,y,z;
int main()
{
	x=0;
	y=1;
	z=1;
	scanf("%d",&n);
	n--;
	while (n--)
	{
		z=x+y;
		x=y;
		y=z;
	}
	printf("%lld\n",z);
	return 0;
}

【3.1】减法

#include <bits/stdc++.h>
  using namespace std;
int n;
long long x,y;
int main()
{
	x=1;
	y=1;
	scanf("%d",&n);
	if (n==1)
	{
		printf("1\n");
		return 0;
	}
	n-=2;
	while (n--)
	{
		y+=x;
		x=y-x;
	}
	printf("%lld\n",y);
	return 0;
}

【3.2】交换

#include <bits/stdc++.h>
  using namespace std;
int n;
long long x,y;
int main()
{
	x=0;
	y=1;
	scanf("%d",&n);
	if (n==1)
	{
		printf("1\n");
		return 0;
	}
	while (n--)
	{
		y+=x;
		swap(x,y);
	}
	printf("%lld\n",x);
	return 0;
}

如发现蒟蒻的错误,请各位大佬在评论区指出或私信!谢谢!qwq

posted @ 2022-03-23 11:47  Jason142  阅读(36)  评论(0编辑  收藏  举报