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 | // the Euler sieve |
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
欧拉函数也接触了很长一段时间了,刻在 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 中的相关解释,讲的很清楚。