试除法求欧拉函数
利用唯一分解定理,得到公式:n乘所有质因数乘积
#include <iostream>
#include <algorithm>
using namespace std;
int phi(int n) {
int res = n;
for(int i = 2; i <= n/i; ++i){
if(n%i==0){
res = 1ll * res * (i - 1)/i; //注意会暴int
while(n%i==0) n /= i;
}
}
if(n > 1) res = 1ll * res * (n - 1)/n;
return res;
}
int main(){
int n;
cin >> n;
while(n--){
int a;
cin >> a;
cout << phi(a) << endl;
}
return 0;
}
⭐线性筛筛欧拉函数
跟线性筛质数的模板类似,多了一个phi数组记录每个数的欧拉函数
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e6+10;
int prim[N];
bool vis[N];
int cnt;
int phi[N];
void get_phi(int n) {
phi[1] = 1;
for(int i = 2; i <= n; ++i){
if(!vis[i]) prim[cnt++] = i, phi[i] = i - 1; //最主要的变化是带入公式求phi
for(int j = 0; 1ll * i * prim[j] <= n; ++j) {
long long m = i * prim[j];
vis[m] = 1;
if(i % prim[j] == 0){
phi[m] = prim[j] * phi[i];
break;
}else{
phi[m] = (prim[j] - 1) * phi[i];
}
}
}
}
int main(){
int n;
cin >> n;
get_phi(n);
long long res = 0;
for(int i = 1; i <= n; ++i){
res+=phi[i];
}
cout << res << endl;
return 0;
}
题目
题目 | 难度 |
---|---|
Acwing.欧拉函数 | 模板题 |
Acwing.筛法求欧拉函数 | 模板题 |