Question 252. Euler Function - ETF - Euler Totient Function


Question 252. Euler Function - ETF - Euler Totient Function


The Euler function φ(n) represents the number of numbers that are less than or equal to n and n are relatively prime. For example φ(1)=1[1], φ(4)=2[1,3].

1. The topic

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

2. Problem solving

This question requires you to find the Euler function of multiple numbers. You can use the Euler sieve linear solution in the prime number sieve method. Of course, you must know several properties of the Euler function before this:
① When two numbers a, b mutually is a prime number, that is, when gcd(a,b)=1, the Euler function φ(a*b)=φ(a)*φ(b)
②φ(n)=n*Π(pi-1/pi)
③When When n is a prime number, φ(n)=n-1
can be deduced as follows (screenshot from oi-wiki):
insert image description here

#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;
    }
}

For a detailed explanation of Euler's sieve to solve the Euler function of multiple numbers, see oi-wiki and other detailed explanations about Euler's function


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324346947&siteId=291194637