数论——Fibonacci数列(C++)

源代码:

#include<cstdio>
int n;
void x1(int x,int y)
{
    x-=2; //利用规律:[F(n),F(n-1)]=[F(n-1),F(n-2)]*[1,1/1,0]。
    int t1=1,t2=0,t3=0,t4=1; //在矩阵乘法中,[1,1/1,1]的作用并不等于1的作用。
    int x1=1,x2=1,x3=1,x4=0;
    while (x)
    {
        if (x%2)
        {
            int y1=t1,y2=t2,y3=t3,y4=t4;
            t1=((y1*x1)%y+(y2*x3)%y)%y;
            t2=((y1*x2)%y+(y2*x4)%y)%y;
            t3=((y3*x1)%y+(y4*x3)%y)%y;
            t4=((y3*x2)%y+(y4*x4)%y)%y;
        }
        x/=2;
        int y1=x1,y2=x2,y3=x3,y4=x4;
        x1=((y1*y1)%y+(y2*y3)%y)%y;
        x2=((y1*y2)%y+(y2*y4)%y)%y;
        x3=((y3*y1)%y+(y4*y3)%y)%y;
        x4=((y3*y2)%y+(y4*y4)%y)%y;
    } //矩阵快速幂。
    printf("%d
",(t1+t3)%y);
}
int main()
{
    scanf("%d",&n);
    for (int a=1;a<=n;a++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        x1(x+1,y); //注意,此Fibonacci数列从0开始。
    }
    return 0;
} 
原文地址:https://www.cnblogs.com/koruko/p/5190263.html