longlongqpow(longlong x,int n,longlong mod){ longlong res = 1; while(n>0) { if(n&1) // 二进制最低位为1,则乘上x^(2^i) res = res * x % mod; x = x * x % mod; n >>= 1; } return res; }
快速幂方法2:
若n为奇数,那么 ans=(x2)2n×x
1 2 3 4 5 6 7 8 9
// n&1 : (x^2)^(n/2)*x longlongmod_pow(longlong x,int n,longlong mod){ if(n==0) return1; longlong res = mod_pow(x * x % mod, n / 2, mod); if(n&1) res = res * x % mod; return res; }