Elegant fibonacci numbers again
Time Limit : 3000/1000ms (Java/Other) Memory Limit : 65535/32768K (Java/Other)
Total Submission(s) : 15 Accepted Submission(s) : 3
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
Fibonacci numbers are nice simple integers. All of you are familiar with it, aren’t you?
The Fibonacci sequence <F[n]> are defined by the recurrence:
F[0]=0;
F[1]=1;
F[n]=F[n-1]+F[n-2], for n>1
You know that the value of F[n] increases rapidly when the n becomes larger. So for each test case,output the value F[n] mod m will be ok.
Input
The first line of the input is a positive integer.It is the number of the test cases followed. Each test case contains two integers n (0<=n<2^32) and m (0<m<10000). There may be one or several spaces between the two integers.
Output
The output of the program should consist of one line of output for each test case.The output of each test case only contains one integer which equals to the value F[n] mod m. No any redundant spaces are needed.
Sample Input
2
1 1000
2 100
Sample Output
1
#include<cstdio>
struct node
{
int f[2][2];
};
node mul(node a,node b,int mod)//矩阵相乘
{
node ret;
ret.f[0][0]=(a.f[0][0]*b.f[0][0]+a.f[0][1]*b.f[1][0])%mod;
ret.f[0][1]=(a.f[0][0]*b.f[0][1]+a.f[0][1]*b.f[1][1])%mod;
ret.f[1][0]=(a.f[1][0]*b.f[0][0]+a.f[1][1]*b.f[1][0])%mod;
ret.f[1][1]=(a.f[1][0]*b.f[0][1]+a.f[1][1]*b.f[1][1])%mod;
return ret;
}
node mypow(node x,int e,int mod)//矩阵幂取模
{
node ret,temp;
if(e==0)
{
x.f[0][0]=1; x.f[0][1]=0;
x.f[1][0]=0; x.f[1][1]=1;
}
if(e==1) return x;
temp=mypow(x,e/2,mod);//二分求矩阵幂 x^e=x^(e/2)*x^(e^2);
ret=mul(temp,temp,mod);
if(e%2==1) ret=mul(ret,x,mod);//如果e是奇数,那还需要乘以x
return ret;
}
int main()
{
int t,n,m;
node x;
scanf("%d",&t);
while(t--)
{
scanf("%d %d",&n,&m);
x.f[0][0]=1; x.f[0][1]=1;
x.f[1][0]=1; x.f[1][1]=0;
if(n)
{
x=mypow(x,n-1,m);//算出初始矩阵的n-1次方 然后相乘
printf("%d\n",x.f[0][0]);//即为 f[n];
}
else printf("0\n");
}
return 0;
}