Fibonacci
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 23141 | Accepted: 15652 |
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
#include <algorithm> //STL通用算法
#include <bitset> //STL位集容器
#include <cctype>
#include <cerrno>
#include <clocale>
#include <cmath>
#include <complex> //复数类
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque> //STL双端队列容器
#include <exception> //异常处理类
#include <fstream>
#include <functional> //STL定义运算函数(代替运算符)
#include <limits>
#include <list> //STL线性列表容器
#include <map> //STL 映射容器
#include <iomanip>
#include <ios> //基本输入/输出支持
#include<iosfwd> //输入/输出系统使用的前置声明
#include <iostream>
#include <istream> //基本输入流
#include <ostream> //基本输出流
#include <queue> //STL队列容器
#include <set> //STL 集合容器
#include <sstream> //基于字符串的流
#include <stack> //STL堆栈容器
#include <stdexcept> //标准异常类
#include <streambuf> //底层输入/输出支持
#include <string> //字符串类
#include <utility> //STL通用模板类
#include <vector> //STL动态数组容器
#include <cwchar>
#include <cwctype>
#define mod 10000
#define ll long long
using namespace std;
struct Mat
{
ll m[101][101];
};//结构体存矩阵
Mat a,e;//a是输入的矩阵,e是单位矩阵
ll n,p;
Mat Mul(Mat x,Mat y) //矩阵乘
{
Mat c;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
c.m[i][j]=0;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
for(int k=1; k<=n; k++)
c.m[i][j]=c.m[i][j]%mod+x.m[i][k]*y.m[k][j]%mod;
return c;
}
Mat pow(Mat x,ll y) //矩阵快速幂
{
Mat ans=e;
while(y)
{
if(y&1)
ans=Mul(ans,x);
x=Mul(x,x);
y>>=1;
}
return ans;
}
int main()
{
//输入
while(scanf("%lld",&p))
{
if(p==-1)return 0;
n=2;
a.m[1][1]=a.m[1][2]=a.m[2][1]=1;
//算法核心
for(int i=1; i<=n; i++)
e.m[i][i]=1;
Mat ans=pow(a,p);
//输出
cout<<ans.m[1][2]%mod<<endl;
}
return 0;
}