光速幂
光速幂
对于
令
于是就可以预处理出
然后
预处理在
根据欧拉定理
const int mod = 1e9 + 7, BL = sqrt(mod);
int B;
int a, b, p;
int qp[2][BL + 10]; //0:a^t%p,1:a^is%p
void init(int a) { //预处理底数为 a
B = sqrt(mod);
qp[0][0] = qp[1][0] = 1;
for (rg int i = 1; i <= B; i++) qp[0][i] = qp[0][i - 1] * a % mod;
for (rg int i = 1; i <= B; i++) qp[1][i] = qp[1][i - 1] * qp[0][B] % mod;
}
int phi(int x) {
rg int res = x;
for (rg int i = 2; i * i <= x; i++) {
if (x % i == 0) res = res / i * (i - 1);
while (x % i == 0) x /= i;
}
if (x > 1) res = res / x * (x - 1);
return res;
}
int qpow(int b) { //求 a^b%mod
b %= phi(mod);
return qp[0][b % B] * qp[1][b / B] % mod;
}