You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

##AcWing 873. 欧拉函数

一、题目描述

给定 n 个正整数 a_i,请你求出每个数的欧拉函数。

欧拉函数的定义

输入格式 第一行包含整数 n

接下来 n 行,每行包含一个正整数 a_i

输出格式 输出共 n 行,每行输出一个正整数 a_i 的欧拉函数。

数据范围 1≤n≤100,1≤a_i≤2×10^9

输入样例:

3
3
6
8

输出样例:

2
2
4

Code

#include <bits/stdc++.h>
using namespace std;

// 求单个数的欧拉函数值
int phi(int x) {
    int res = x;
    // 不要写在i*i<=x, 可能会造成爆int
    for (int i = 2; i <= x / i; i++)
        if (x % i == 0) {              // 暴力枚举所有因子
            res = res / i * (i - 1);   // 套一下欧拉函数公式
            while (x % i == 0) x /= i; // 只与质因子有关,与幂次无关,应除尽除
        }
    if (x > 1) res = res / x * (x - 1); // 最后一个大因子
    return res;
}

int main() {
    int n;
    cin >> n;
    while (n--) {
        int x;
        cin >> x;
        printf("%d\n", phi(x));
    }
    return 0;
}