1. 程式人生 > 其它 >斐波那契數列程式碼實現優化

斐波那契數列程式碼實現優化

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