HDU 4549 M斐波那契数列(矩阵快速幂+欧拉定理)

M斐波那契数列

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others)
Total Submission(s): 353    Accepted Submission(s): 93


Problem Description
M斐波那契数列F[n]是一种整数数列,它的定义如下:

F[0] = a
F[1] = b
F[n] = F[n-1] * F[n-2] ( n > 1 )

现在给出a, b, n,你能求出F[n]的值吗?
 
Input
输入包含多组测试数据;
每组数据占一行,包含3个整数a, b, n( 0 <= a, b, n <= 10^9 )
 
Output
对每组测试数据请输出一个整数F[n],由于F[n]可能很大,你只需输出F[n]对1000000007取模后的值即可,每组数据输出一行。
 
Sample Input
0 1 0 6 10 2
 
Sample Output
0 60
 
Source
 
Recommend
liuyiding
 
 
这题的话,看a ,b 的指数,刚好可以使用斐波那契数列求解。
 
然后用矩阵做。
 
A^B %C   这题的C是质素,而且A,C是互质的。
所以直接A^(B%(C-1)) %C
 
比较一般的结论是 A^B %C=A^( B%phi(C)+phi(C) ) %C     B>=phi(C)
 
 
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
using namespace std;
const int MOD=1e9+7;

struct Matrix
{
    long long mat[2][2];
};
Matrix mul(Matrix a,Matrix b)
{
    Matrix ret;
    for(int i=0;i<2;i++)
        for(int j=0;j<2;j++)
        {
            ret.mat[i][j]=0;
            for(int k=0;k<2;k++)
            {
                ret.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
                ret.mat[i][j]%=(MOD-1);
            }
        }
    return ret;
}
Matrix pow_M(Matrix a,int n)
{
    Matrix ret;
    memset(ret.mat,0,sizeof(ret.mat));
    ret.mat[0][0]=ret.mat[1][1]=1;
    Matrix temp=a;
    while(n)
    {
        if(n&1)ret=mul(ret,temp);
        temp=mul(temp,temp);
        n>>=1;
    }
    return ret;
}
long long pow_m(long long a,long long n)
{
    long long ret=1;
    long long temp=a%MOD;
    while(n)
    {
        if(n&1)
        {
            ret*=temp;
            ret%=MOD;
        }
        temp*=temp;
        temp%=MOD;
        n>>=1;
    }
    return ret;
}
int main()
{
    int a,b,n;
    Matrix tmp;
    tmp.mat[0][0]=0;
    tmp.mat[0][1]=tmp.mat[1][0]=tmp.mat[1][1]=1;
    while(scanf("%d%d%d",&a,&b,&n)==3)
    {
        Matrix p=pow_M(tmp,n);
        //printf("%d %d %d %d\n",p.mat[0][0],p.mat[1][0],p.mat[0][1],p.mat[1][1]);
        int ans=(pow_m(a,p.mat[0][0])*pow_m(b,p.mat[1][0]))%MOD;
        printf("%d\n",ans);
    }
    return 0;
}
 
 
 
 
 
人一我百!人十我万!永不放弃~~~怀着自信的心,去追逐梦想
原文地址:https://www.cnblogs.com/kuangbin/p/3090793.html