zoukankan      html  css  js  c++  java
  • hdu4549之矩阵快速幂

    M斐波那契数列

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

    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

    分析:F[2]=F[1]*F[0],F[3]=F[2]*F[1]=F[1]^2*F[0],F[4]=F[1]^3*F[0]^2...==>F[n]=F[1]^f(n-1) * F[0]^f(n-2);//f(n)表示第n个斐波那契数

    所以只要求a^f(n-2) * b^f(n-1),但是f(n)将非常大(超过64位),这时候就要知道有个费马小定理了:(a^b)%mod =a^( b%(mod-1) )%mod

    #include<iostream>
    #include<cstdio>
    #include<cstdlib>
    #include<cstring>
    #include<string>
    #include<queue>
    #include<algorithm>
    #include<map>
    #include<vector>
    #include<iomanip>
    #define INF 99999999
    using namespace std;
    
    const int MAX=10;
    const int mod=1000000007;
    __int64 sum[2][2],array[2][2]; 
    
    void MatrixMult(__int64 a[2][2],__int64 b[2][2]){
    	__int64 c[2][2];
    	c[0][0]=a[0][0]*b[0][0]+a[0][1]*b[1][0];
    	c[0][1]=a[0][0]*b[0][1]+a[0][1]*b[1][1];
    	c[1][0]=a[1][0]*b[0][0]+a[1][1]*b[1][0];
    	c[1][1]=a[1][0]*b[0][1]+a[1][1]*b[1][1];
    	for(int i=0;i<2;++i){
    		for(int j=0;j<2;++j)a[i][j]=c[i][j]%(mod-1);
    	}
    }
    
    int Matrix(int k){
    	array[0][0]=0;
    	array[0][1]=array[1][0]=array[1][1]=1;
    	while(k){
    		if(k&1)MatrixMult(sum,array);
    		MatrixMult(array,array);
    		k>>=1;
    	}
    	return (sum[0][0]+sum[0][1])%(mod-1);
    }
    
    __int64 FastPower(__int64 a,int k){
    	__int64 ans=1;
    	while(k){
    		if(k&1)ans=(ans*a)%mod;
    		a=(a*a)%mod;
    		k>>=1;
    	}
    	return ans;
    }
    
    int main(){
    	__int64 a,b,n;
    	while(cin>>a>>b>>n){
    		if(n<2){printf("%I64d
    ",n?b:a);continue;}
    		sum[0][0]=sum[1][1]=1;
    		sum[0][1]=sum[1][0]=0;
    		int i=Matrix(n-2);
    		int j=Matrix(1);
    		printf("%I64d
    ",(FastPower(a,i)*FastPower(b,j))%mod);
    	}
    	return 0;
    }


  • 相关阅读:
    English,The Da Vinci Code, Chapter 23
    python,meatobject
    English,The Da Vinci Code, Chapter 22
    English,The Da Vinci Code, Chapter 21
    English,The Da Vinci Code, Chapter 20
    English,The Da Vinci Code, Chapter 19
    python,xml,ELement Tree
    English,The Da Vinci Code, Chapter 18
    English,The Da Vinci Code, Chapter 17
    English,The Da Vinci Code, Chapter 16
  • 原文地址:https://www.cnblogs.com/riskyer/p/3235437.html
Copyright © 2011-2022 走看看