Number Theory

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Euclidean algorithm

gcd(0, a) = a

gcd(a, b) = gcd(b - a, a) b = 25
= gcd(b mod a, a) a = 7

gcd(10, 120) b-a = 18


= gcd(110, 10) b-a = 11
= gcd(100, 10) b-a = 4
= gcd(90, 10) gcd(a, b)
... = gcd(b, a)
= gcd(10, 10)
= gcd(0, 10)
= 10
int gcd(int a, int b) {
if (a == 0) return b;
if (b == 0) return a;
if (b > a) {
return gcd(b % a, a);
}
return gcd(a % b, b);
}

__gcd(a, b)
a, b

smallest c, such that a|c, b|c

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

vector<bool> mark(n + 1, true);


mark[0] = mark[1] = false;
for (int d = 2; d <= n; d++) {
if (!mark[d]) {
cout << d << " ";
}
for (int a = 2 * d; a <= n; a += d) {
mark[a] = false;
}
}

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

m = pb11 · pb22 · pb33 · pbkk

max(a1 ,b1 ) max(a2 ,b2 ) max(b3 ,a3 ) max(ak ,bk )


lcm(n, m) = p1 · p2 · p3 · pk
n = pa1 1 · pa2 2 · pa3 3 · pakk

(1 + p1 + p21 + · · · + pa1 k )(1 + p2 + p22 + · · · + pa2 2 ) · · · (1 + pk + p2k + · · · + pakk )

You might also like