【矩阵快速幂专题】POJ 3070 Fibonacci

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qian2213762498/article/details/82153450

http://poj.org/problem?id=3070

Fibonacci

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 19290   Accepted: 13357

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, …

An alternative formula for the Fibonacci sequence is

.

Given an integer n, your goal is to compute the last 4 digits of Fn.

Input

The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ n ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.

Output

For each test case, print the last four digits of Fn. If the last four digits of Fn are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print Fn mod 10000).

Sample Input

0
9
999999999
1000000000
-1

Sample Output

0
34
626
6875

思路

题目要求给定一个n,求Fibonacci序列的第n项,因为n值上限很大,裸的矩阵快速幂模板题。

关键点在于矩阵B的构造。最终C矩阵等于A*B^(n-2)次幂,其中C矩阵的第【0】【0】项即为F(n).

AC Code

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
const ll nmax=3;
const ll MOD=10000;
#define mod(x) ((x)%MOD)

int n;
struct mat{
	ll m[nmax][nmax];
}unit;

//A*B^(n-2)=C //C矩阵的首项即为f(n) 
mat operator *(mat a,mat b){
	mat ret;
	ll x;
	for(ll i=0;i<nmax;i++){//3*3
		for(int j=0;j<nmax;j++){
			x=0;
			for(ll k=0;k<nmax;k++){
				x+=mod((ll)a.m[i][k]*b.m[k][j]);
			}
			ret.m[i][j]=mod(x);
		}
	}
	return ret;
}

void init_unit(){
	for(ll i=0;i<nmax;i++){
		unit.m[i][i]=1;
	} 
	return;
}
mat pow_mat(mat a,ll n){//求矩阵a的n次幂 
	mat ret=unit;
	while(n){
		if(n&1) ret=ret*a;
		a=a*a;
		n>>=1;
	} 
	return ret;
}
int main(int argc, char** argv) {
	ll n;
	init_unit();
	while((cin>>n)&&(n!=-1)){//需要求矩阵B的n-2次幂 
		if(n==0) printf("0\n");
		else if(n==1) printf("1\n");
		else if(n==2) printf("1\n");
		else{
			mat a,b;
			b.m[0][0]=1;b.m[0][1]=1;b.m[0][2]=0;
			b.m[1][0]=1;b.m[1][1]=0;b.m[1][2]=1;
			b.m[2][0]=0;b.m[2][1]=0;b.m[2][2]=0;
			
			a.m[0][0]=1;a.m[0][1]=1;a.m[0][2]=0;
			b=pow_mat(b,n-2);
			a=a*b;
			//printf("%lld\n",mod(a.m[0][0]));
			printf("%lld\n",a.m[0][0]%MOD);
		} 
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qian2213762498/article/details/82153450