【POJ】3070 Fibonacci(矩阵乘法)

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

根据本题算矩阵,用快速幂即可。

裸题

#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
#define rep(i, n) for(int i=0; i<(n); ++i)
#define for1(i,a,n) for(int i=(a);i<=(n);++i)
#define for2(i,a,n) for(int i=(a);i<(n);++i)
#define for3(i,a,n) for(int i=(a);i>=(n);--i)
#define for4(i,a,n) for(int i=(a);i>(n);--i)
#define CC(i,a) memset(i,a,sizeof(i))
#define read(a) a=getint()
#define print(a) printf("%d", a)
#define dbg(x) cout << #x << " = " << x << endl
#define printarr(a, n, m) rep(aaa, n) { rep(bbb, m) cout << a[aaa][bbb]; cout << endl; }
inline const int getint() { int r=0, k=1; char c=getchar(); for(; c<'0'||c>'9'; c=getchar()) if(c=='-') k=-1; for(; c>='0'&&c<='9'; c=getchar()) r=r*10+c-'0'; return k*r; }
inline const int max(const int &a, const int &b) { return a>b?a:b; }
inline const int min(const int &a, const int &b) { return a<b?a:b; }
typedef int matrix[2][2];
matrix a, b;
const int M=10000;
int n;
inline void mul(matrix a, matrix b, matrix c, const int &la, const int &lb, const int &lc, const int &MOD) {
	matrix t;
	rep(i, la) rep(j, lc) {
		t[i][j]=0;
		rep(k, lb) t[i][j]=(t[i][j]+(a[i][k]*b[k][j])%MOD)%MOD;
	}
	rep(i, la) rep(j, lc) c[i][j]=t[i][j];
}
int main() {
	while(~scanf("%d", &n) && n!=-1) {
		b[0][0]=b[1][1]=1;
		a[0][0]=a[0][1]=a[1][0]=1;
		b[0][1]=b[1][0]=a[1][1]=0;
		while(n) {
			if(n&1) mul(a, b, b, 2, 2, 2, M);
			mul(a, a, a, 2, 2, 2, M);
			n>>=1;
		}
		printf("%d\n", b[1][0]);
	}
	return 0;
}

 

 


 

 

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

Hint

As a reminder, matrix multiplication is associative, and the product of two 2 × 2 matrices is given by

.

Also, note that raising any 2 × 2 matrix to the 0th power gives the identity matrix:

.

Source

posted @ 2014-08-30 09:17  iwtwiioi  阅读(285)  评论(0编辑  收藏  举报