Professional Documents
Culture Documents
Number Theory
Number Theory
Number Theory
gcd(0, a) = a
gcd(a, b) = gcd(b - a, a) b = 25
= gcd(b mod a, a) a = 7
__gcd(a, b)
a, b
lcm(15, 10) = 30
find all divisors of n
36
1, 2, 3, 4, 6, 9, 12, 18, 36
for (int i = 1; i * i <= n; i++) {
if (n % i == 0) {
// i is a factor
if (i != n / i) {
// n / i is another factor
}
}
}
find all divisors of all numbers from 1 to
n
n = 6
1
1 2
1 3
1 2 4
1 5
1 2 3 6
vector<int> divisors[n + 1];
for (int d = 1; d <= n; d++) {
for (int a = d; a <= n; a += d) {
divisors[a].push_back(d);
}
}
// divisors[i] contains all divisors of i
vector<int> a;
a.push_back(1);
find all primes from 1 to n
n = 15
2, 3, 5, 7, 11, 13
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
sieve of erasthones
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
vector<bool> mark(n + 1, true);
mark[0] = mark[1] = false;
for (int d = 2; d <= n; d++) {
if (!mark[d]) {
// d is a prime
for (int a = d * d; a <= n; a += d) {
mark[a] = false;
}
}
}
Every positive integer other than 1 has
an unique prime factorization.
vector<pair<int, int>> v;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
int power = 0;
while (n % i == 0) {
power++;
n /= i;
}
v.push_back({i, power});
}
}
if (n != 1) v.push_back({n, 1});
n = pa1 1 · pa2 2 · pa3 3 · pakk