Fibonacci
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 15 Accepted Submission(s) : 6
Problem 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
<span lang="en-us"><p>The input test file will contain multiple test cases. Each test case consists of a single line containing n (where 0 ≤ <i>n</i> ≤ 1,000,000,000). The end-of-file is denoted by a single line containing the number −1.</p></span>
Output
<span lang="en-us"><p>For each test case, print the last four digits of <i>F<sub>n</sub></i>. If the last four digits of <i>F<sub>n</sub></i> are all zeros, print ‘0’; otherwise, omit any leading zeros (i.e., print <i>F<sub>n</sub></i> mod 10000).</p></span>
Sample Input
0 9 999999999 1000000000 -1
Sample Output
0 34 626 6875
Source
PKU
快速幂模板:
long long modexp(long long a, long long b, int mod)
{
long long res=1;
while(b>0)
{
//a=a%mod;(有时候n的值太大了会超出long long的储存,所以要先取余)
if(b&1)//&位运算:判断二进制最后一位是0还是1,&的运算规则为前后都是1的时候才是1,奇数偶数判断;
res=res*a%mod;
b=b>>1;//相当于除以2;
a=a*a%mod;
}
return res;
}
代码:
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
struct fast_mod
{
int t[2][2];
};
fast_mod matrixmul(fast_mod a,fast_mod b)
{
int i,j,k;
fast_mod c;
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
c.t[i][j]=0;
for(k=0; k<2; k++)
{
c.t[i][j]+=(a.t[i][k]*b.t[k][j])%10000;
}
}
}
return c;
}
int main()
{
int n,i;
while(scanf("%d",&n),n!=-1)
{
if(!n)
{
printf("0\n");
continue;
}
fast_mod s;
s.t[0][0]=s.t[0][1]=s.t[1][0]=1;
s.t[1][1]=0;
fast_mod ans;
memset(ans.t,0,sizeof(ans.t));
for(i=0; i<2; i++)
{
ans.t[i][i]=1;
}
while(n)
{
if(n&1)
ans=matrixmul(ans,s);
n=n>>1;
s=matrixmul(s,s);
}
cout<<ans.t[0][1]%10000<<endl;
}
}