国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

從sicily Fibonacci 問題出發解決矩陣快速冪求解斐波那契額問題

2019-11-06 06:43:32
字體:
來源:轉載
供稿:網友

/*********************************************************************************************************************************/

寫在前面:

一直不敢打代碼,生怕各種WA會暴露我的智商;

但是已經大二了,轉眼就要面臨升學還是工作的神圣選擇;

非常虛,于是開了個博客慢慢回顧一下這些年來學的一些或易或難的算法

最好能寫成一部勵志史詩吧hhhh。

/*********************************************************************************************************************************/

題目描述(Description)

In the Fibonacci integer sequence, F0 = 0, F1 = 1, and Fn = Fn-1 + Fn-2 for n ≥ 2. For example, the first ten terms of the Fibonacci sequence are:0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …  Given an integer n, your goal is to compute the last Fn mod (10^9 + 7).輸入要求(Input)

  The input test file will contain a single line containing n (n ≤ 2^31-1).

There are multiple test cases!

輸出要求(Output)For each test case, PRint the Fn mod (10^9 + 7).樣例Sample InputCopy sample input to clipboard
     9Sample Output
     34提示(hint)

  You may need to use "long long".

/*********************************************************************************************************************************/

題意分析:

對下標為n的斐波那契數列元素進行取模;

在這里有幾點注意:

1.遞歸代碼雖然簡潔,但是占用空間過多,容易造成內存泄漏;

2.鑒于n的取值實在是大的突破天際,采用簡單的遞推方法肯定會出現超時;

比較之下,應該采用一種新方法——矩陣快速冪

矩陣快速冪

什么是快速冪?

       快速冪是一種快速求解矩陣高次方的方法,能夠將樸素的O(n)的復雜度降到O(log(n))

  

什么是斐波那契數列

斐波那契數列的定義:An = An-1 + An-2, a0 = 0, a1 = 1;

  斐波那契數列進行矩陣變換

/**********************************************************************************************************************************/

代碼實現:

#include <iostream>using namespace std;#define Maxinum  1000000007struct Matrix{	long long mat[2][2];};Matrix mul(Matrix a, Matrix b){	Matrix res;	for(int i = 0; i < 2; i++)	{		for(int j = 0; j < 2; j++)		{			res.mat[i][j] = 0;			for(int k = 0; k < 2; k++)			{				res.mat[i][j] += a.mat[i][k] * b.mat[k][j];				res.mat[i][j] %= Maxinum;			}					}	}	return res;}Matrix quickpower(Matrix a, Matrix b, long long n){	while(n)	{		if(n & 1) b = mul(b, a);        //按位與操作符,用來判斷是不是 		//if(n % 2 == 1) b = mul(b,a); 		a = mul(a, a);		n >>= 1;		//移位,表示其除以二 			}	return b;}int main(){	Matrix a = {1,1,1,0};	long long n;	while(cin >> n)	{		Matrix b = {1,0,0,1};		if(n == 0) 			cout << 0 << endl;		else 		{			Matrix temp = quickpower(a, b, n - 1);			cout << temp.mat[0][0] << endl;		}	}	return 0;}


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 龙井市| 济阳县| 临漳县| 改则县| 新竹市| 静宁县| 清水河县| 道真| 古田县| 忻州市| 双桥区| 普定县| 明光市| 确山县| 浦东新区| 浙江省| 诏安县| 东山县| 陕西省| 牟定县| 竹山县| 玉林市| 登封市| 启东市| 南投县| 郁南县| 黑河市| 延川县| 武威市| 沭阳县| 临海市| 边坝县| 鲜城| 灯塔市| 余干县| 东台市| 越西县| 海安县| 三门峡市| 汉中市| 吉木乃县|