1. 程式人生 > >M斐波那契數列

M斐波那契數列

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

思路詳情:

https://www.cnblogs.com/kuangbin/archive/2013/05/21/3090793.html(解答程式幹了什麼)

https://www.cnblogs.com/huxianglin/p/5995649.html(解答程式的數學問題)

AC C++:

#include <cstring>
#include <cstdio>

const int MOD=1e9+7;

struct Matrix
{
    long long mat[2][2];
    Matrix()
    {
    	memset(mat,0,sizeof(mat));
	}
	//建構函式在程式開始時自動執行 
	//與之相反地是解構函式,在程式結束時自動執行,函式前有“~”。 
};

Matrix mul(Matrix a,Matrix b)
{
    Matrix result;
    for(int i=0;i<2;i++)
        for(int j=0;j<2;j++)
            for(int k=0;k<2;k++)
            {
                result.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
                result.mat[i][j]%=(MOD-1);
                //運用了費馬小定理,所以是 MOD-1 ,不是MOD 
            }
        
    return result;
}

Matrix pow_Mat(Matrix a,int n)
{
    Matrix result;
    result.mat[0][0]=result.mat[1][1]=1;
//先把結果矩陣寫成 I 矩陣 
    
    Matrix temp=a;
    while(n)
    {
        if(n&1)result=mul(result,temp);
        temp=mul(temp,temp);
        n>>=1;
    }
    return result;
}


long long pow_mum(long long a,long long n)
{
    long long result=1;
    long long temp=a%MOD;
    while(n)
    {
        if(n&1)
        {
            result*=temp;
            result%=MOD;
        }
        temp*=temp;
        temp%=MOD;
        n>>=1;
    }
//這個地方時正常取餘,所以是MOD 

    return result;
}

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) 
//scanf()函式返回值是 :成功賦值的資料項數
    {
        Matrix p=pow_Mat(tmp,n);
        int ans=(pow_mum(a,p.mat[0][0])*pow_mum(b,p.mat[1][0]))%MOD;
//因為斐波那契的第一項是1,第零項 是 0,所以剛好兩個矩陣相乘最終結果就是2*2矩陣的第一列 
        printf("%d\n",ans);
    }
    return 0;
}