-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtotient_function.cpp
More file actions
43 lines (34 loc) · 902 Bytes
/
totient_function.cpp
File metadata and controls
43 lines (34 loc) · 902 Bytes
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
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
-> Totient function
-> phi(n) = sum (gcd(i, n) == 1) for 1 <= i <= n
-> ref: https://cp-algorithms.com/algebra/phi-function.html
*/
vector<int> primes;
// calculating phi(n) in O(sqrt(n))
int totient(int n) {
int res = n;
for (int i = 0; primes[i] * primes[i] <= n; ++i) {
if (n % primes[i] == 0) {
while (n % primes[i] == 0)
n /= primes[i];
res -= res / primes[i];
}
}
if (n > 1)
res -= res / n;
return res;
}
vector<int> phi(N);
// calculating phi() for 1..N in O(NloglogN)
void totientAll() {
for (int i = 1; i < N; ++i)
phi[i] = i;
for (int i = 2; i < N; ++i) {
if (phi[i] == i) {
for (int j = i; j < N; j += i) {
phi[j] /= i;
phi[j] *= (i - 1);
}
}
}
}