题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;
}
}
三、单个数的欧拉函数求解
如何求解单个数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;
}