1. 程式人生 > >Colossal Fibonacci Numbers! UVA - 11582

Colossal Fibonacci Numbers! UVA - 11582

入門 loss code sig img com ssa div cstring

技術分享

題解:所有計算都是對n取模的,不妨設F(i) = f(i) mod n。不難發現,當二元組(F(i),F(i+1))出現重復時,整個序列就開始重復。因為余數最多

n種,所以最多n2 項就會出現重復。設周期為M,則只需要計算出F[0]~F[n2],然後算出F[ab]等於其中哪一項就可以了。

------------------------------------------------------------------摘自《算法競賽入門經典》

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4
#include<algorithm> 5 using namespace std; 6 typedef unsigned long long ull; 7 8 const int maxn=1005; 9 10 ull a,b,n; 11 int temp; 12 int F[maxn*maxn]; 13 14 ull mod_pow(ull x,ull y,ull mod){ 15 ull ans=1; 16 while(y>0){ 17 if(y&1) ans=ans*x%mod; 18 x=x*x%mod;
19 y>>=1; 20 } 21 return ans; 22 } 23 24 void inite(){ 25 F[0]=0,F[1]=1%n; 26 temp=1; 27 for(int i=2;i<=(n*n+100);i++){ 28 F[i]=(F[i-1]+F[i-2])%n; 29 if(F[i]==1&&F[i-1]==0){ temp=i-1; break; } 30 } 31 } 32 33 void solve(){ 34 ull ans=mod_pow(a%temp,b,(ull)temp); //a一定要先模一遍,否則會溢出
35 cout<<F[ans]<<endl; 36 } 37 38 int main() 39 { int kase; 40 cin>>kase; 41 while(kase--){ 42 cin>>a>>b>>n; 43 inite(); 44 solve(); 45 } 46 return 0; 47 }

Colossal Fibonacci Numbers! UVA - 11582