Fibonacci Check-up

来源:互联网 发布:php软件指的是什么 编辑:程序博客网 时间:2024/05/19 09:12

这道题是Fibonacci 的变形

首先尝试算出1到10大的答案通过找规律,发现他也是Fibonacci 序列

1 3 8 21 55这些个数也都是斐波那契数啊,而且Sn=F2*n,比如S3=8=F6............然后再敲,1A。

构建矩阵是要这样构建的:

E - Fibonacci Check-up
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Submit Status

Description

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

21 300002 30000

Sample Output

13


1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
#include <iostream>#include <cstdio>#include <cstring>using namespace std;struct matrix{    int ma[3][3];};int mod;matrix mult(matrix a,matrix b){    matrix ans;    memset(ans.ma,0,sizeof(ans.ma));    for(int i=1;i<=2;i++)    {        for(int j=1;j<=2;j++)        {            for(int k=1;k<=2;k++)            {                ans.ma[i][j]+=(a.ma[i][k]*b.ma[k][j])%mod;            }            ans.ma[i][j]%=mod;        }    }    return ans;}matrix pow(matrix x,int n){    matrix ans;    memset(ans.ma,0,sizeof(ans.ma));    for(int i=1;i<=2;i++)    {        ans.ma[i][i]=1;    }    while(n)    {        if(n&1)        {            ans=mult(ans,x);        }        x=mult(x,x);        n>>=1;    }    return ans;}int main(){    int t,n;    scanf("%d",&t);    while(t--)    {        scanf("%d %d",&n,&mod);        if(n==0)        {            printf("0\n");            continue;        }        matrix sum;        sum.ma[1][1]=sum.ma[1][2]=sum.ma[2][1]=1;        sum.ma[2][2]=0;        sum=pow(sum,2*n);        printf("%d\n",sum.ma[1][2]);    }    return 0;}


0 0