#include <cstdio>#include<iostream>using namespacestd;Const intMOD =10000;structmatrix{intm[2][2];} ans,BaseMatrix multi (matrix A, matrix B) {matrix tmp; for(inti =0; I <2; ++i) { for(intj =0; J <2; ++j) {Tmp.m[i][j]=0; for(intK =0; K <2; ++k) Tmp.m[i][j]= (Tmp.m[i][j] + a.m[i][k] * b.m[k][j])%MOD; } } returntmp;}intFast_mod (intN//to find the n power of Matrix base{ Base. m[0][0] =Base. m[0][1] =Base. m[1][0] =1; Base. m[1][1] =0; ans.m[0][0] = ans.m[1][1] =1;//ans initialized to the unit matrixans.m[0][1] = ans.m[1][0] =0; while(n) {if(N &1)//implementation of ans *= t; where ans is first assigned to TMP and then ans = tmp * t{ans= multi (ans,Base); } Base= multi (Base,Base); N>>=1; } returnans.m[0][1];}intMain () {intN; while(SCANF ("%d", &n) && n! =-1) {printf ("%d\n", Fast_mod (n)); } return 0;}
is actually the principle of fast power!
Matrix Quick Power Template