您的位置:首页 > 其它

hdu-2855 Fibonacci Check-up

2017-11-24 19:27 387 查看
Every ALPC has his own alpc-number just like alpc12, alpc55, alpc62 etc.

As more and more fresh man join us. How to number them? And how to avoid their alpc-number conflicted?

Of course, we can number them one by one, but that’s too bored! So ALPCs use another method called Fibonacci Check-up in spite of collision.

First you should multiply all digit of your studying number to get a number n (maybe huge).

Then use Fibonacci Check-up!

Fibonacci sequence is well-known to everyone. People define Fibonacci sequence as follows: F(0) = 0, F(1) = 1. F(n) = F(n-1) + F(n-2), n>=2. It’s easy for us to calculate F(n) mod m.

But in this method we make the problem has more challenge. We calculate the formula , is the combination number. The answer mod m (the total number of alpc team members) is just your alpc-number.

Input

First line is the testcase T.

Following T lines, each line is two integers n, m ( 0<= n <= 10^9, 1 <= m <= 30000 )

Output

Output the alpc-number.

Sample Input

2
1 30000
2 30000


Sample Output

1
3


解题思路:

和的形式为二项式展开,故所求为
(A+E)^n
,E为单位矩阵,然后快速幂;

#include <stdio.h>
#include <string.h>

struct Matrix{
int arr[2][2];
};
int n,mod;
Matrix Mul(Matrix a,Matrix b)
{
Matrix c;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
{
c.arr[i][j]=0;
for(int k=0;k<2;k++)
c.arr[i][j]=(c.arr[i][j]+a.arr[i][k]*b.arr[k][j]%mod)%mod;
c.arr[i][j]%mod;
}
return c;
}
Matrix Pow(Matrix a,int m)
{
Matrix b;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
if(i==j)
b.arr[i][j]=1;
else
b.arr[i][j]=0;
while(m)
{
if(m&1==1)
b=Mul(b,a);
a=Mul(a,a);
m>>=1;
}
return b;
}
int main ()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&mod);
Matrix orig;
for(int i=0;i<2;i++)
for(int j=0;j<2;j++)
orig.arr[i][j]=1;
orig.arr[0][0]=2;
Matrix ans;
ans=Pow(orig,n);
printf("%d\n",ans.arr[0][1]%mod);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: