// 快速幂 intquick_pow(int base, int exponent){ int res = 1 % MOD; base %= MOD; while (exponent) { if (exponent & 1) res = res * base % MOD; base = base * base % MOD; exponent >>= 1; } return res; }
// 费马小定理求逆元 inlineintinv(int primal){ returnquick_pow(primal, MOD - 2); }
// 扩欧求逆元. 不要求模是质数. 复杂度: O(log(modulo)) constint MOD = 1000000007;
// 扩展欧几里得 int _exgcd(int a, int b, int &x, int &y) { int d = a; if (b != 0) { d = _exgcd(b, a % b, y, x); y -= (a / b) * x; } else { x = 1; y = 0; } return d; } inlineboolexgcd(int a, int b, int c, int &x, int &y){ int _x, _y, g; g = _exgcd(a, b, _x, _y); if (c % g) returnfalse; int p = b / g; x = (c / g * _x % p + p) % p; y = (c - a * x) / b; returntrue; }
// 线性同余方程 inlineintlinear_congruence_theorem(int a, int c, int m){ int x, y; bool flag = exgcd(a, m, c, x, y); return flag ? x : -1; }