Difference between revisions of "Multiply, Power and Inverse"
Jump to navigation
Jump to search
(Created page with " == Power == <syntaxhighlight lang='cpp'> LL bin(LL x, LL n, LL MOD) { LL ret = MOD != 1; for (x %= MOD; n; n >>= 1, x = x * x % MOD) if (n & 1) ret = ret * x...") |
|||
Line 51: | Line 51: | ||
<syntaxhighlight lang='cpp'> | <syntaxhighlight lang='cpp'> | ||
− | LL inv(LL x, LL MOD) { return | + | LL inv(LL x, LL MOD) { return bin(x, MOD - 2, MOD); } |
</syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 11:56, 6 March 2018
Power
LL bin(LL x, LL n, LL MOD) {
LL ret = MOD != 1;
for (x %= MOD; n; n >>= 1, x = x * x % MOD)
if (n & 1) ret = ret * x % MOD;
return ret;
}
To prevent intermediate result exceeds the range of long long:
LL bin(LL x, LL n, LL MOD) {
LL ret = MOD != 1;
for (x %= MOD; n; n >>= 1, x = mul(x, x, MOD))
if (n & 1) ret = mul(ret, x, MOD);
return ret;
}
Multiply
LL mul(LL a, LL b, LL m) {
LL ret = 0;
while (b) {
if (b & 1) {
ret += a;
if (ret >= m) ret -= m;
}
a += a;
if (a >= m) a -= m;
b >>= 1;
}
return ret;
}
[math]\displaystyle{ O(1) }[/math] version:
LL mul(LL u, LL v, LL p) {
return (u * v - LL((long double) u * v / p) * p + p) % p;
}
Inverse
LL inv(LL x, LL MOD) { return bin(x, MOD - 2, MOD); }