题252.欧拉函数-ETF - Euler Totient Function


题252.欧拉函数-ETF - Euler Totient Function


欧拉函数φ(n)表示的是小于等于n和n互质的数的个数。比如φ(1)=1 [1],φ(4)=2 [1、3]。

一、题目

In number theory, the totient φ of a positive integer n is defined to be the number of positive integers less than or equal to n that are coprime to n.

Given an integer n (1 <= n <= 10^6). Compute the value of the totient φ.

Input
First line contains an integer T, the number of test cases. (T <= 20000)

T following lines, each contains an integer n.

Output
T lines, one for the result of each test case.

Example
Input:
5
1
2
3
4
5

Output:
1
1
2
2
4

二、题解

本题要你求多个数的欧拉函数,可以采用素数筛法中的欧拉筛线性求解,当然在此之前必须得知道几个关于欧拉函数的性质:
①当两个数a,b互为质数,即gcd(a,b)=1时,欧拉函数φ(a*b)=φ(a)*φ(b)
②φ(n)=n*Π(pi-1/pi)
③当n是质数时,有φ(n)=n-1
则可做如下推导(截图自oi-wiki):

在这里插入图片描述
代码如下:

#include <bits/stdc++.h>

using namespace std;

const int maxn=1e6+1;

int p[maxn],cnt;
int vis[maxn];
int phi[maxn];

void getEuler(int n)//写之前可先把欧拉筛写出来,然后去改动
{
    phi[1]=1;//1的欧拉函数值等于1
    for(int i=2;i<=n;i++)
    {
        if(!vis[i])
        {
            p[++cnt]=i;
            phi[i]=i-1;//质数的欧拉函数值等于该数-1
        }
        for(int j=1;j<=cnt;j++)
        {
            if(i*p[j]>n)
            {
                break;
            }
            vis[i*p[j]]=1;
            if(i%p[j]==0)//i有因子为p[j],p[j]不再是i*p[j]的最小素因子
            {
                phi[i*p[j]]=phi[i]*p[j];//根据推导出的公式可知,i*p[j]的欧拉函数值等于i的欧拉函数值乘以p[j]这个素数
                break;
            }
            else
            {
                phi[i*p[j]]=phi[i]*phi[p[j]];//根据推导出的公式可知
            }
        }
    }
}

int main()
{
    getEuler(1e6);
    int T;
    cin>>T;
    for(int i=0;i<T;i++)
    {
        int n;
        cin>>n;
        cout<<phi[n]<<endl;
    }
}

欧拉筛求解多个数的欧拉函数详解见oi-wiki以及关于欧拉函数的其他详解

三、单个数的欧拉函数求解

如何求解单个数n的欧拉函数?根据如下公式:
在这里插入图片描述
我们可以记一个结果res=n,通过唯一分解定理将组成n的质因子pi分解出来,然后每次除以pi,乘以pi-1,最终res即为n的欧拉函数phi(n)。
代码如下:

int getEuler(int n)
{
    int res=n;
    for(int i=2;i<=n/i;i++)
    {
        if(n%i==0)
        {
            res=res/i*(i-1);
            while(n%i==0) n/=i;
        }
    }
    if(n>1) res=res/n*(n-1);
    return res;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值