When the MoD is a large number p, there are times when multiplication may explode long, using fast multiply or fast power.
Reference: http://www.cnblogs.com/whywhy/p/5066730.html
First on the template:
Quick multiply:
ll multi (ll a,ll b,ll m) { ll ans=0; while (b) { if(b&1) (ans+=a)%= m; (A=a*2)%= m; b/=2; } return ans;}
Fast power:
ll Pow_mod (ll a,ll b,ll m) { ll res=1; while (b) { if(b&1) Res=multi (res,a,m); // We're going to use a fast ride here. A=multi (a,a,m); b/=2; } return Res;}
Quick Multiply + fast power hdu topic link (puzzle)
Another is: Matrix fast power, according to the topic analysis, and then establish the relevant matrix, and then use the fast power;
Matrix Fast Power:
Node mult (node A,node b)//The calculation of the matrix{node T; for(intI=0;i<2; i++) for(intj=0;j<2; j + +) {T.m[i][j]=0; for(intp=0;p <2;p + +) T.m[i][j]= ((T.m[i][j]+a.m[i][p]*b.m[p][j])%mod+mod)%MOD; } returnt;}voidPow_mod (Long LongN) {original.m[0][0]=1, original.m[0][1]=-1; original.m[1][0]=1, original.m[1][1]=0; ans.m[0][0]=ans.m[1][1]=1; ans.m[0][1]=ans.m[1][0]=0;//Initialize ans to 2-order matrix E while(n) {if(n%2==1) ans=mult (ans,original); Original=mult (original,original); N/=2; }}
Two-way matrix fast power:
CF 450B (solution) POJ 3070 Fibonacci Matrix Rapid Power New method
Fast multiplication, fast power (Matrix fast Power)