首页 > 代码库 > POJ 3070 Fibonacci

POJ 3070 Fibonacci

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

Fibonacci

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 10796 Accepted: 7678

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

Stanford Local 2006

大意——给你一个求解Fibonacci数列的公式。问:给出一个数n,要你用这个公式计算出F(n)的后四位。

思路——题目已经告诉我们用矩阵连乘求Fibonacci数,问题是n非常大。假设直接矩阵乘n-1次,肯定TLE。因此我们能够用二分求高速幂:

技术分享

复杂度分析——时间复杂度:O(n),空间复杂度:O(1)


附上AC代码:


#include <iostream>
#include <cstdio>
#include <string>
#include <cmath>
#include <iomanip>
#include <ctime>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
typedef unsigned int UI;
typedef long long LL;
typedef unsigned long long ULL;
typedef long double LD;
const double PI = 3.14159265;
const double E = 2.71828182846;
const int MOD = 10000;
struct matrix
{
	int mat[2][2];
} res, base; // 定义一个结构体封装矩阵

matrix mul(matrix a, matrix b); // 矩阵乘法运算
int fast_mod(int x); // 二分求高速幂
// a^n = (a^(n/2))^2 当n为偶数
// a^n = a*(a^(n/2))^2 当n为奇数

int main()
{
	ios::sync_with_stdio(false);
	int num;
	while (cin >> num && num != -1)
	{
		cout << fast_mod(num) << endl;
	}
	return 0;
}

matrix mul(matrix a, matrix b)
{
	matrix temp;
	for (int i=0; i<2; ++i)
		for (int j=0; j<2; ++j)
		{
			temp.mat[i][j] = 0;
			for (int k=0; k<2; ++k)
				temp.mat[i][j] = (temp.mat[i][j]+a.mat[i][k]*b.mat[k][j])%MOD;
		}
	return temp;
}

int fast_mod(int x)
{
	base.mat[0][0]=base.mat[0][1]=base.mat[1][0]=1;
	base.mat[1][1]=0; // 原始矩阵
	res.mat[0][0]=res.mat[1][1]=1;
	res.mat[0][1]=res.mat[1][0]=0; // 单位矩阵
	while (x)
	{
		if (x & 1) // 相当于模2
		{
			res = mul(res, base);
		}
		base = mul(base, base);
		x >>= 1; // 相当于除2
	}
	return res.mat[0][1];
}


POJ 3070 Fibonacci