1. 程式人生 > >C++實現求斐波那契數列的第n項

C++實現求斐波那契數列的第n項

斐波那契數列,即1、1、2、3、5、8、13、21、34、55……,規律是從第三項開始,每個數都是前兩個數之和。用程式設計實現求它的第n項,程式碼如下:

#include"E:\C++ h\big_number_f.h"
#include<iostream>
using namespace std;
int main(){
	int n;
	cin>>n;
	string a="1",b="1",c;
	for(int i=2;i<=n;i++){
		c=plus_pos(a,b);
		a=b,b=c;
	}
	cout<<a;
	return 0;
}

函式版:

#include"E:\C++ h\big_number_f.h"
#include<iostream>
using namespace std;
string f(int x){
	string a="1",b="1",c;
	for(int i=2;i<=x;i++){
		c=plus_pos(a,b);
		a=b,b=c;
	}
	return a;
}
int main(){
	int n;
	cin>>n;
	cout<<f(n); 
	return 0;
}

其中用到的高精度數函式見此部落格:用string容器實現大整數比較、加、減、乘和除(用減法實現)(函式版)

。(地址:https://mp.csdn.net/postedit/84843656(注:E:\C++ h\big_number_f.h是高精度函式程式碼在我的計算機中存放的路徑)

速度:n=10000時不到一秒;n=100000時約需要13秒。

歡迎轉載,但請在文章中附加上本文連結:https://blog.csdn.net/weixin_41461277/article/details/84937945  。