yennnn
則 \(n\) 為質數(prime)
反之,則稱 \(n\) 為合數
\(eg:28 = 1 + 2 + 4 + 7 + 14\)
\[ \pi(n) \approx \frac{n}{\ln n}\]
\(若k為合數,則必有k = mn,其中k, m, n \in \mathbb{N}\)
\(且必有m \leq \sqrt k或n \leq \sqrt k\)
bool prime(int n) {
if (n < 2) return false;
for (int x = 2; x*x <= n; x++) {
if (n%x == 0) return false;
}
return true;
}
複雜度:\(O(\sqrt n)\)
就...一直除以質因數
vector<int> factors(int n) {
vector<int> f;
for (int x = 2; x*x <= n; x++) {
while (n%x == 0) {
f.push_back(x);
n /= x;
}
}
if (n > 1) f.push_back(n);
return f;
}
複雜度:\(O(\sqrt n)\)
vector<int> prime(0);
int prime_table(){
prime.push_back(2);
for (int j = 3; j <= 2147483647; j++) {
if (isPrime(j)) {
prime.push_back(j);
}
}
return 0;
}
bool isPrime(int n) {
if (n < 2) return false;
for (int x = 0; prime[x]*prime[x] <= n; x++) {
if (n%x == 0) return false;
}
return true;
}
複雜度:\(O(n\sqrt n)\)
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
---|---|---|---|---|---|---|---|---|---|
11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 |
for (int x = 2; x <= n; x++) {
if (sieve[x]) continue;
for (int u = 2*x; u <= n; u += x) {
sieve[u] = x;
}
}
複雜度:\(O(n \log \log n)\)
\(gcd(a, b) = gcd(a, a\%b)\)
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a%b);
}
複雜度:\(O(log n)\)
條件:
\(ax + by = c存在整數解 若且唯若 gcd(a, b) \mid c\)
void extgcd(int a, int b, int& x, int& y, int& d) {
if (b == 0) {
d = a;
x = 1;
y = 0;
return;
}
else {
extgcd(b, a % b, x, y, d);
int nx = y;
int ny = x - (a / b) * y;
x = nx;
y = ny;
return;
}
}
複雜度:\(O(log n)\)
複雜度:\(O(n)\)
int modpow(int x, int n, int m) {
if (n == 0) return 1%m;
long long u = modpow(x,n/2,m);
u = (u*u)%m;
if (n%2 == 1) u = (u*x)%m;
return u;
}
複雜度:\(O(log n)\)
我們記為\(a \equiv r \pmod b\)
若\(ax \equiv 1 \pmod m\)
\(我們稱a為x的模逆元,記作x^{-1}\)
模逆元存在條件:
\(gcd(a, m) = 1\)
所以\(a^{p - 2} \)為 \(a\) 的模逆元
所以\(a^{\varphi(m) - 1} \)為 \(a\) 的模逆元
用擴展歐幾里得演算法