Number Theory
Prime
Greatest Common Divisor
Block
Euler's Totient Funciton
質數
1. Definition
2. Primality test
3. Sieve of Eratosthenes
Prime
Definition
定義
Prime
Primality Tests
怎麼判斷一個數是不是質數
Prime
試除法
枚舉看是否能整除
bool isPrime(int a) {
if (a < 2) return false;
for (int i = 2; i < a; i++) {
if (a % i == 0) return false;
}
return true;
}
bool isPrime(int a) {
if (a < 2) return false;
for (int i = 2; i * i < a; i++) {
if (a % i == 0) return false;
}
return true;
}
Prime
Sieve of Eratothenes
vector<bool> is_prime(n + 1, true);
is_prime[0] = is_prime[1] = false;
for (int i = 2; i * i <= n; i++) {
if (is_prime[i]) {
for (int j = i * i; j <= n; j += i) {
is_prime[j] = false;
}
}
}
最大公因數
1. 歐基里德算法
2. LCM
3. 擴展歐幾里德算法
GCD
歐基里德算法
GCD
Implement
// Version 1
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
// Version 2
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
int gcd(int a, int b) {
while (b != 0) {
int tmp = a;
a = b;
b = tmp % b;
}
return a;
}
GCD
Least Common Multiple (LCM)
#include <numeric> // 在這裡面
// ...
std::gcd(a, b);
std::lcm(a, b);
GCD
擴展歐基里德算法
GCD
Implement
int exgcd(int a, int b, int &x, int &y) {
if (b == 0) {
x = 1;
y = 0;
return a;
}
int d = exgcd(b, a % b, x, y);
int t = x;
x = y;
y = t - (a / b) * y;
return d;
}
數論分塊(應該沒特定英文名)
Block
分塊
Block
Implement
long long sum(long long n) {
long long ret = 0, i = 0;
while (i <= n) {
long long val = n / i; // floor(n / i)
long long r = n / val; // 讓 floor(n / k) = val 的區間右界
if (r > n) r = n;
ret += val * (r - i + 1);
i = r + 1;
}
return ret;
}
歐拉函數
1. Property
2. Divisor Sum Property
Euler's totient function
性質
Euler's totient function
性質
Euler's totient function
Implement
int phi(int n) {
int result = n;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
while (n % i == 0) {
n /= i;
}
result -= result / i;
}
}
if (n > 1) { // n is prime
return n - 1;
}
return result;
}
Euler's totient function
Implement
void phi_1_to_n(int n) {
vector<int> phi(n + 1);
for (int i = 0; i <= n; i++)
phi[i] = i;
for (int i = 2; i <= n; i++) {
if (phi[i] == i) {
// i is prime
for (int j = i; j <= n; j += i) {
phi[j] -= phi[j] / i;
}
}
}
}
Euler's totient function
Divisor Sum Property
Euler's totient function
Euler's Theorem
void phi_1_to_n(int n) {
vector<int> phi(n + 1);
phi[0] = 0;
phi[1] = 1;
for (int i = 2; i <= n; i++) {
phi[i] = i - 1;
}
for (int i = 2; i <= n; i++) {
for (int j = 2 * i; j <= n; j += i) {
phi[j] -= phi[i];
}
}
}
題單