C++版本:
费马小定理求逆元
a^(p-2)是a在模p意义下的乘法逆元(p为质数)。
求最大公约数
int gcd(int a, int b) {
if (b == 0)return a;
return gcd(b, a%b);
}
埃氏筛法
int sieve(int n) {
int p = 0;
for (int i = 0; i <= n; i++)is_prime[i] = true;
is_prime[0] = is_prime[1] = false;
for (int i = 2; i <= n; i++) {
if (is_prime[i]) {
prime[p++] = i;
for (int j = 2 * i; j <= n; j += i)is_prime[j] = false;
}
}
return p;
}
区间筛法
void segment_sieve(ll a, ll b) {
for (int i = 0; (ll)i*i <= b; i++)is_prime_small[i] = true;
for (int i = 0; i < b - a; i++)is_prime[i] = true;
for (int i = 2; (ll)i*i < b; i++) {
if (is_prime_small[i]) {
for (int j = 2 * i; (ll)j*j < b; j += i)is_prime_small[j] = false;
for (ll j = max(2LL, (a + i - 1) / i)*i; j < b; j += i)is_prime[j - a] = false;
}
}
}
快速幂
ll mod_pow(ll x, ll n, ll mod) { //快速幂
ll res = 1;
while (n > 0) {
if (n & 1)res = res * x%mod;
x = x * x%mod;
n >>= 1;
}
return res;
}