题目
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.
中文
在Fibonacci整数序列中,F0 = 0, F1=1,和Fn = Fn−1 + Fn−2为n例如,Fibonacci序列的前十个项是:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
Fibonacci序列的另一个公式是
.
给定整数n,您的目标是计算Fn.
输入
输入测试文件将包含多个测试用例。每个测试用例由包含n(其中0≤)的一行组成。n(≤1,000,000,000)。文件的结尾由包含数字−1的一行表示.
输出
对于每个测试用例,打印˚F ñ。如果最后四位数˚F ñ均为零,打印‘0’;否则,省略任何前导零(即打印)。ñ10000)。
样本输入
0
9
999999999
1000000000
-1
样本输出
0
34
626
6875
暗示
作为提醒,矩阵乘法是相联的,并给出了两个2×2矩阵的乘积
.
另外,请注意,将任意2×2矩阵提升到第0次方会给出恒等矩阵:
.
题目链接:Fibonacci
思路
求矩阵,输出结果矩阵res的第二行第一列的数即为所求
代码
#include <iostream>
#include <algorithm>
#include <memory.h>
using namespace std;
typedef long long ll;
#define mod 10000
ll n;
const int N=2;
ll tmp[N][N];
void mul(ll a[][N],ll b[][N],ll n)
{
memset(tmp,0,sizeof(tmp));
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
for(int k=0;k<n;k++)
tmp[i][j]=(tmp[i][j]+a[i][k]*b[k][j])%mod;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
a[i][j]=tmp[i][j];
}
ll res[N][N];
void Pow(ll a[][N],ll n)
{
memset(res,0,sizeof res);
for(int i=0;i<N;i++)
res[i][i]=1;
while(n){
if(n&1)
mul(res,a,N);
mul(a,a,N);
n>>=1;
}
}
int main()
{
while(cin>>n&&n!=-1){
ll vis[N][N]={{1,1},{1,0}};
Pow(vis,n);
cout<<res[1][0]<<endl;
}
return 0;
}