# 欧拉函数

## 定义

Euler's totient function counts the positive integers up to a given integer n that are relatively prime to n.

## 计算公式

$\varphi(n)=n \prod_{p | n}\left(1-\frac{1}{p}\right)$

### 引理及其证明

$\begin{array}{l}{\text { If } p \text { is prime and } k \geq 1 \text { , then }} \\ {\qquad \varphi\left(p^{k}\right)=p^{k-1}(p-1)=p^{k}\left(1-\frac{1}{p}\right)}\end{array}$

### 计算公式的证明

$$n=p_{1}^{k_{1}} \cdots p_{r}^{k_{r}}$$

\begin{aligned} \varphi(n) &=\varphi\left(p_{1}^{k_{1}}\right) \varphi\left(p_{2}^{k_{2}}\right) \cdots \varphi\left(p_{r}^{k_{r}}\right) \\ &=p_{1}^{k_{1}}\left(1-\frac{1}{p_{1}}\right) p_{2}^{k_{2}}\left(1-\frac{1}{p_{2}}\right) \cdots p_{r}^{k_{r}}\left(1-\frac{1}{p_{r}}\right) \\ &=p_{1}^{k_{1}} p_{2}^{k_{2}} \cdots p_{r}^{k_{r}}\left(1-\frac{1}{p_{1}}\right)\left(1-\frac{1}{p_{2}}\right) \cdots\left(1-\frac{1}{p_{r}}\right) \\ &=n\left(1-\frac{1}{p_{1}}\right)\left(1-\frac{1}{p_{2}}\right) \cdots\left(1-\frac{1}{p_{r}}\right) \end{aligned}

## 筛法

### $$\sqrt n$$筛

inline int getphi(int x) {
int tmp = sqrt(x), res = x;
for (int i = 1; i <= tmp; i++) {
if (x % i == 0) {
res -= res / i;
while (x % i == 0) x /= i;
}
}
return x > 1 ? res - res / x : res;
}


### 埃氏筛

inline int getphi(int x){
for(int i=2;i<=x;i++){
if(phi[i])continue;//和数
for(int j=i;j<=x;j+=i){
if(!phi[j])phi[j]=j;
phi[j]=phi[j]/i*(i-1);
}
}
return 0;
}


### 线性筛

void get_phi() {
phi[1]=1
for(int i=2;i<=n;i++) {
if(!pri[i])phi[i]=i-1,pri[++num]=i;
for(int j=1;j<=num&&i*pri[j]<=n;j++) {
pri[i*pri[j]]=1;
if(i%pri[j]==0){phi[i*pri[j]]=phi[i]*pri[j];break;}
else phi[i*pri[j]]=phi[i]*phi[pri[j]];
}
}
}


posted @ 2019-11-15 11:03  GavinZheng  阅读(234)  评论(0编辑  收藏  举报