1. Fast Power
37=?
【Analysis】 7 = 111
31 =3
32 =9
34 =81
……
3 2 ^ (n-1) --n: binary digits 0 ~ n-1
So 3 7 = 3 × 9 × 81
【例1】https://www.acwing.com/problem/content/91/
#include <iostream> using namespace std; int main () { int a, b, p; cin >> a >> b >> p; int res = 1 % p; // answer while (b) { if (b & 1 ) res = res * 1ll * a% p; // Consider from the one bit of b, if the b bit is 1, then res * a // 1ll: longlong integer 1 to prevent overflow
// first multiply the multiplier Factor modulo and then operation does not affect the result, (a * b)% p = (a% p * b% p)% p a = a * 1ll * a% p; // Tens: continuous square b >> = 1 ; //b right by 1 bit, removing bits @ 6 >> 1 is changed to a right 00000110 00000011 } COUT << RES << endl; return 0 ; }