快速乘原理同快速幂
不做赘述
ll qmul(ll a, ll b, ll mod) //快速乘
{
ll ans = 0;
while(b)
{
if(b & 1)
ans = (ans + a) % mod;
a = (a + a) % mod;
b >>= 1;
}
return ans;
}
ll qpow(ll a, ll b, ll mod) //快速幂
{
ll ret = 1;
a %= mod;
while(b)
{
if(b & 1)
ret = mul(ret, a, mod) % mod;
a = mul(a, a, mod), mod;
b >>= 1;
}
return ret;
}
方法2
将模运算全部转换为加减法运算, 即使爆数据也不会造成%模运算错误
a * b % p = a * b - floor(a / p * b) * p;
ll qmul_db(ll a, ll b, ll mod)
{
ll cnt = ld(a) * b / mod;
ll ans = a * b - cnt * mod;
if(ans < 0)
ans += mod;
else if( ans > mod)
ans -= mod;
return ans;
}