代码改变世界

Fibonacci(矩阵快速幂)

2019-08-02 09:19  木木王韦  阅读(181)  评论(0)    收藏  举报

Fibonacci

菲波那契数列是指这样的数列: 数列的第一个是0和第二个数是1,接下来每个数都等于前面2个数之和。 给出一个正整数a,要求菲波那契数列中第a个数的后四位是多少。
Input
多组数据 -1结束 范围1~10^9
Output
第x项的后4位
Sample Input
0
9
999999999
1000000000
-1
Sample Output
0
34
626
6875

| F(2) 1 | * | 1 1 | = | F(3) 1 |
| F(1) 0 | * | 1 0 | = | F(2) 0 |

| 1 1 | 的n次方 = | F(n) 1 |
| 1 0 | 的n次方 = | F(n-1) 0 |

ac代码:

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;

int mod=10000;
struct node{
	int m[4][4];
};
node mul(node a,node b){
	node ans;
	memset(ans.m ,0,sizeof(ans.m ));
	for(int i=1;i<=2;i++){
		for(int j=1;j<=2;j++){
			for(int k=1;k<=2;k++){
				ans.m[i][j] =(ans.m[i][j] +a.m[i][k]*b.m[k][j]%mod+mod )%mod;
			}
		}
	}
	return ans;
}

node ksm(node a,long long int b){
	node res;
	memset(res.m,0,sizeof(res.m));
	for(int i=1;i<=2;i++){
		res.m [i][i]=1;
	}
	while(b){
		if(b&1){
			res=mul(res,a);
		}
		b>>=1;
		a=mul(a,a);
	}
	return res;
}

int main(){
	long long int n;
	while(cin>>n){
		if(n==-1) break;
		if(n==0){
			cout<<"0"<<endl;
		}
		else if(n==1){
			cout<<"1"<<endl;
		}
		else{
			node a,b;
		a.m [1][1]=1;
		a.m [1][2]=1;
		a.m [2][1]=1;
		a.m [2][2]=0;
		b=ksm(a,n);
		cout<<b.m [1][2]<<endl;
		
		}
		
	}
	return 0;
}