long long mod_pow(int a,int n,int p)
{
long long ret=1;
long long A=a;
while(n)
{
if (n & 1)
ret=(ret*A)%p;
A=(A*A)%p;
n>>=1;
}
return ret;
}
中间防止溢出的快速幂取模:
LL modular_multi(LL a, LL b, LL c) {// a * b % c
LL res, temp;
res = 0, temp = a % c;
while (b) {
if (b & 1) {
res += temp;
if (res >= c) {
res -= c;
}
}
temp <<= 1;
if (temp >= c) {
temp -= c;
}
b >>= 1;
}
return res;
}
LL modular_exp(LL a, LL b, LL c) { //a ^ b % c 改成mod_pow就不行,中间发生了溢出,还是这个模板靠谱
LL res, temp;
res = 1 % c, temp = a % c;
while (b) {
if (b & 1) {
res = modular_multi(res, temp, c);
}
temp = modular_multi(temp, temp, c);
b >>= 1;
}
return res;
}
LL gcd(LL a, LL b) {
if (a < b) {
a ^= b, b ^= a, a ^= b;
}
if (b == 0) {
return a;
}
if (!(a & 1) && !(b & 1))
return gcd(a >> 1, b >> 1) << 1;
else if (!(b & 1))
return gcd(a, b >> 1);
else if (!(a & 1))
return gcd(a >> 1, b);
else
return gcd(b, a - b);
}