Use two points to change the complexity from O (n) to O (Logn)
#include <iostream> #include <cstdio>using namespace std;///(b^n) mod m; (a*b mod m) = (a mod m) * (b mod m) mod m O (log n)//(b^n) mod m; (a) MoD m = ((a mod m)-(b mod m) + N) mod m ) O (log n)//(b^n) mod m; (A + b) mod m = ((a mod m) + (b mod m) mod m ) O (log n) int mod (int b,int n,int m)//bitwise operation { int ans=1; while (n) { if (n&1) ans= (ans*b)%m; b= (b*b)%m; n=n>>1; } return ans;} int mod_1 (int b,int n,int m)// O (log n) recursive { if (n==0) return 1; int x=mod_1 (b,n/2,m); Long Long ans= (long Long) x*x%m; if (n%2) ans=ans*b%m; N&1 return (int) ans; int main () { int b,n,m; while (scanf ("%d%d%d", &b,&n,&m)) { printf ("%d ", mod (b,n,m)); printf ("%d\n", Mod_1 (B,n,m)); } return 0;} /**12996 227 37909 = = 7775*/
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Fast Power-Take mode