~~求欧拉函数(附模板题)

模板

int phi(int x)
{
    int res = x;
    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;
}

在这里插入图片描述

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

int main(){
    int n;
    cin>>n;
    while(n--){
        int x;
        cin>>x;
        int res=x;
        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);
        cout<<res<<endl;
    }
    return 0;
}

发布了164 篇原创文章 · 获赞 440 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_45884316/article/details/105220810