算法 BISHI73 【模板】欧拉函数计算Ⅰ ‖ 朴素求值:试除法 思路 求解代码 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 44 45 46 47 48 49 50 51 52 53 54 55 56 public static void main(String[] args) throws IOException { // 使用BufferedReader读取输入,PrintWriter输出结果 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); // 读取测试用例数量 int T = Integer.parseInt(br.readLine().trim()); // 处理每个测试用例 for (int i = 0; i < T; i++) { long x = Long.parseLong(br.readLine().trim()); out.println(euler(x)); // 输出当前测试用例的结果 } // 清空输出缓冲区并关闭资源 out.flush(); out.close(); br.close(); } /** * 使用欧拉函数计算小于等于x的正整数中与x互质的数的个数 * 欧拉函数公式:φ(n) = n * (1 - 1/p1) * (1 - 1/p2) * ... * (1 - 1/pk) * 其中p1, p2, ..., pk是n的质因数 * * @param x 需要计算欧拉函数的正整数 * @return 小于等于x的正整数中与x互质的数的个数 */ private static long euler(long x) { // 如果x为1,直接返回1,因为1与1互质 if (x == 1) { return 1; } // 初始化结果为x long res = x; // 遍历从2到√x的所有数,寻找x的质因数 for (long i = 2; i * i <= x; i++) { // 如果i是x的因数 if (x % i == 0) { // 应用欧拉函数公式,乘以(1-1/i) res = res / i * (i - 1); // 去除x中所有的i因子 while (x % i == 0) { x /= i; } } } // 如果x大于1,说明x本身是一个质数,应用欧拉函数公式 if (x > 1) { res = res / x * (x - 1); } return res; }