Colossal Fibonacci Numbers! UVA

题解:所有计算都是对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 } 
原文地址:https://www.cnblogs.com/zgglj-com/p/7363183.html