Euler’s Totient Function.

Definition. Euler’s Totient Function $\varphi(N)$ is defined as the number of positive integers $\leq N$ that are relatively prime to $N$, where $1$ is counted as being relatively prime to all integers.

The general case of Euler’s Totient is $\varphi(n)=n\Pi_{p|n}(1-\frac{1}{p})=n(1-\frac{1}{p_1})(1-\frac{1}{p_2})…(1-\frac{1}{p_r})$. This is essentially the Inclusion-Exclusion principle.

Code Implementation: Linear Sieve

To calculate a specific totient of $n$, we could design a trivial $O(n\log n)$ algorithm based on the above formula. However, there exists a sieve algorithm that could calculate totients of number $1$ to $n$ in linear time $O(n)$. Below is the code in C++:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// the Euler sieve
// bool array: is_prime, int array: prime, phi

void sieve() {
for (int i = 1; i < N; ++i) is_prime[i] = 1;
cnt = 0;
is_prime[1] = 0;
phi[1] = 1;
for (int i = 2; i <= N; ++i) {
if (is_prime[i]) {
prime[++cnt] = i;
phi[i] = i - 1; // for a prime p, phi[p] = p - 1
}
for (int j = 1; j <= cnt && i * prime[j] <= N; ++j) {
is_prime[i * prime[j]] = 0;
if (i % prime[j])
phi[i * prime[j]] = phi[i] * phi[prime[j]];
else {
phi[i * prime[j]] = phi[i] * prime[j];
break;
}
}
}
}

Reference & Explanation: (OI Wiki) Linear Sieve for Euler’s totient function

Euler’s Theorem

Theorem. Let $n$ be a positive integer, and let $a$ be an integer that is relatively prime to $n$. Then $a^{\varphi(n)}\equiv 1\pmod{n}$, where $\varphi(n)$ is Euler’s totient function of $n$.

Since $\gcd(a,n)=1$, $a$ is invertible modulo $n$. According to Euler’s Theorem, $a^{\varphi(n)}\equiv 1\pmod{n}$. Therefore $a\times a^{\varphi(n)-1}\equiv 1\pmod{n}$. $a^{\varphi(n)-1}$ is a multiplicative inverse of $a$ modulo $n$.

An informal proof. (need the knowledge of $\mathbb{Z}_n^{*}$, multiplicative group of integers modulo $n$).

For $a\in\mathbb{Z}n^{*}$, ${r_1,r_2,…r{\varphi(n)}}=(\mathbb{Z}/n)^{*}={ar_1,ar_2,…ar_{\varphi(n)}}$.

Therefore $r_1r_2…r_{\varphi(n)}\equiv (ar_1)(ar_2)…(ar_{\varphi(n)})$, which reduces to $1\equiv a^{\varphi(n)}$. This cancellation is allowed since all $r_i$ have multiplicative inverses modulo $n$.

Reference & Explanation: (Brilliant Math Wiki) Proof of Euler’s Theorem

Eureka moment!

欧拉函数也接触了很长一段时间了,刻在 DNA 里的 $\varphi * \mathbf{1}=\mathbf{Id}$。

这里主要想讲下关于欧拉函数的一般公式:$\varphi(n)=n\Pi_{p|n}(1-\frac{1}{p})$。本质上这是一个容斥原理的应用。

举个例子就容易理解了:假设 $n$ 只有两个质因子 $p_1,p_2$,那么展开上式可得 $\varphi(n)=n-\frac{n}{p_1}-\frac{n}{p_2}+\frac{n}{p_1p_2}$. 用自然语言描述,即在 $1-n$ 中与 $n$ 互质的数的个数为 $n$ 减去是 $p_1$ 倍数的数的个数,再减去是 $p_2$ 倍数的数的个数。此时,是 $p_1p_2$ 倍数的数将会被重复减去两次;根据容斥原理,我们将多减的个数重新加回来,因此最后再加上是 $p_1p_2$ 倍数的数的个数。

关于欧拉函数线性筛算法的设计也十分巧妙,它是建立在质数线性筛的基础上的。具体可见 OI Wiki 中的相关解释,讲的很清楚。