欧拉函数(Euler’s totient function),也称为费马函数,是一个与正整数相关的数论函数,用符号 φ(n) 表示。欧拉函数 φ(n) 定义为小于或等于 n 的正整数中与 n 互质的数的个数。
RSA加密算法(Rivest-Shamir-Adleman)就是通过欧拉函数进行公钥加密。
具体而言,对于给定的正整数 n,欧拉函数 φ(n) 计算满足以下条件的 k 的个数: 1 ≤ k ≤ n,且 k 与 n 互质(即 k 和 n 的最大公约数为 1)。
如φ(10) = 4,其中{1、3、7、9 }与10互质。
欧拉函数计算公式如下:
ϕ
(
n
)
=
n
⋅
(
1
−
1
p
1
)
⋅
(
1
−
1
p
2
)
⋅
…
⋅
(
1
−
1
p
k
)
\phi(n) = n \cdot \left(1 - \frac{1}{p_1}\right) \cdot \left(1 - \frac{1}{p_2}\right) \cdot \ldots \cdot \left(1 - \frac{1}{p_k}\right)
ϕ(n)=n⋅(1−p11)⋅(1−p21)⋅…⋅(1−pk1)
其中 p1, p2, …, pk 是n不同的质因数。(注意,是质因数,不是质数)有想了解质因数的同学可以看我这篇文章:分解质因数
例如,对于正整数 n = 10,我们来计算欧拉函数 φ(10)。首先,我们需要将 n 分解为质因数的乘积形式。
10 可以分解为:
2
×
5
,
2 \times 5,
2×5,
这意味着 10 的质因数为 2 和 5,它们都是不同的质数。
因此可以计算欧拉函数 φ(10) 如下:
ϕ
(
10
)
=
10
⋅
(
1
−
1
2
)
⋅
(
1
−
1
5
)
=
4
\phi(10) = 10 \cdot \left(1 - \frac{1}{2}\right) \cdot \left(1 - \frac{1}{5}\right) = 4
ϕ(10)=10⋅(1−21)⋅(1−51)=4
所以,φ(10) = 4,表示小于或等于 10 的正整数中与 10 互质的数的个数为 4。
可以借助最大公因数实现欧拉函数:
public class Main {
public static int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
public static int eulerTotientFunction(int n) {
int count = 0;
for (int i = 1; i <= n; i++) {
if (gcd(n, i) == 1) {
count++;
}
}
return count;
}
public static void main(String[] args) {
int n = 10;
int result = eulerTotientFunction(n);
System.out.println("欧拉函数 φ(" + n + ") = " + result);
}
}