1 //快速幂取模, 2 #include <iostream> 3 4 using namespace std; 5 //1. 6 //a^n%b 7 int modExp(int a, int n, int b) 8 { 9 int t,y; 10 t=1;y=a; 11 while (n) 12 { 13 if (n&1) t=t*y%b;//若n为偶数; 14 y=y*y%b; 15 n>>=1; 16 } 17 return t; 18 } 19 //2.利用a^n%c = (((a%c)*a)%c......) 20 int modexp_simple(int a,int n,int b) 21 { 22 int ret = 1; 23 while (n--) 24 { 25 ret = a * ret % b; 26 } 27 return ret; 28 } 29 int main() 30 { 31 int a,n,b; 32 while (cin>>a>>n>>b) 33 { 34 cout<<modExp(a,n,b)<<endl; 35 cout<<modexp_simple(a,n,b)<<endl; 36 } 37 38 return 0; 39 }