Fibonacci( POJ-3070)
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 Fnare 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:
.
题目翻译:
在斐波那契整数序列中,当n≥2时,F0 = 0, F1 = 1, Fn = Fn - 1 + Fn - 2。例如,斐波那契数列的前十项是:
0、1、1、2、3、5、8、13、21、34、……
斐波那契数列的另一个公式是
。
给定一个整数n,您的目标是计算Fn的最后4位。
输入
输入测试文件将包含多个测试用例。每个测试用例由包含n的单行组成(其中0≤n≤1000,000,000)。文件末尾用一行表示,其中包含数字- 1。
输出
对于每个测试用例,打印Fn的最后四位。如果Fn的最后四位都是零,则打印“0”;否则,省略任何前导零(即,打印Fn mod 10000)。
思路:
矩阵快速幂模板题
AC代码:
#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
#include <math.h>
const int num=2;
const int mod=10000;
using namespace std;
struct Mat
{
int m[num][num];
};
Mat I
{
1,0,
0,1
};
Mat Mul(Mat a, Mat b)
{
Mat ans;
for(int i=0; i<num; i++)
for (int j=0; j<num; j++)
{
ans.m[i][j]=0;
for (int k=0; k<num; k++)
ans.m[i][j]+=(a.m[i][k]*b.m[k][j]);
ans.m[i][j]%=mod;
}
return ans;
}
Mat pow(Mat a, long long b)
{
Mat ans=I;
Mat sum=a;
while (b>0)
{
if (b & 1)
ans=Mul(ans, sum);
sum=Mul(sum, sum);
b>>=1;
}
return ans;
}
int main()
{
long long n;
Mat a
{
1,1,
1,0
};
while(cin>>n && n!=-1)
{
Mat sum;
sum = pow(a,n);
cout<<sum.m[0][1]<<endl;
}
return 0;
}