HDU 4549 M斐波那契數列(矩陣快速冪3)+費馬小定理
阿新 • • 發佈:2019-02-12
C - M斐波那契數列
Crawling in process...
Crawling failed
Time Limit:1000MS
Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
F[0] = a
F[1] = b
F[n] = F[n-1] * F[n-2] ( n > 1 )
現在給出a, b, n,你能求出F[n]的值嗎?
每組資料佔一行,包含3個整數a, b, n( 0 <= a, b, n <= 10^9 )
對每組測試資料請輸出一個整數F[n],由於F[n]可能很大,你只需輸出F[n]對1000000007取模後的值即可,每組資料輸出一行。
解析:(以下是在網上搜的題解,第一次做沒做出來) 這題的話,看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)
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
Sample Input
0 1 0 6 10 2Sample Output
0 60解析:(以下是在網上搜的題解,第一次做沒做出來) 這題的話,看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<iostream> #include<algorithm> #include<string.h> using namespace std; const int mod=1e9+7; struct matrix{long long mm[2][2];}; matrix mul(matrix a,matrix b) { matrix ans; for(int i=0;i<2;i++) for(int j=0;j<2;j++) { ans.mm[i][j]=0; for(int k=0;k<2;k++) { ans.mm[i][j]+=a.mm[i][k]*b.mm[k][j]; ans.mm[i][j]%=(mod-1); } }return ans; } matrix pow(matrix a,int n) { matrix ans; memset(ans.mm,0,sizeof(ans.mm)); ans.mm[0][0]=ans.mm[1][1]=1; matrix temp=a; while(n) { if(n&1)ans=mul(ans,temp); temp=mul(temp,temp); n>>=1; }return ans; } long long summ(long long a,long long n) { long long ans=1; long long temp=a%mod; while(n) { if(n&1) { ans*=temp; ans%=mod; } temp*=temp; temp%=mod; n>>=1; }return ans; } int main() { int a,b,n; matrix unit; unit.mm[0][0]=0; unit.mm[0][1]=unit.mm[1][0]=unit.mm[1][1]=1; while(cin>>a>>b>>n) { matrix p=pow(unit,n); int ans=(summ(a,p.mm[0][0])*summ(b,p.mm[1][0]))%mod; printf("%d\n",ans); } }