注意事项:
包含分解质因数算法的运用,可以看我之前的文章:java—试除法分解质因数
题目:
输入
3
3
6
8
输出
2
2
4
public class 欧拉函数_公式使用 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int m = in.nextInt();
while (m-- > 0) {
int x = in.nextInt();
//res初始为x, 然后分解质因数, 参考分解质因数的算法, 时间复杂度为O(根号x)
int res = x;
for (int i = 2; i<=x/i; i++) {
if (x % i == 0) {
res = res / i * (i-1); //这里是从res * (1-1/i)化简得到的,先除再乘是防止溢出
while (x % i == 0) x /= i;
}
}
if (x > 1) res = res / x * (x-1);
System.out.println(res);
}
}
}
声明:算法思路来源为y总,详细请见https://www.acwing.com/
本文仅用作学习记录和交流