别的没啥可说的,为了整除出数据,要改写一下公式
N(p1-1/p1)->N/p1(p1-1)
#include<bits/stdc++.h>
using namespace std;
int n;
int main()
{
cin>>n;
while(n--){
int a;
cin>>a;
int res = a;
for( int i = 2; i <= a/i; i++ ){
//i就是一个质因子
if(a%i==0){
res = res/i*(i-1);
while(a%i==0)
a/=i;
}
}
if(a > 1)
res = res/a*(a-1);
cout<<res<<endl;
}
return 0;
}
筛法求欧拉函数
改写线性筛法
如果是素数n,与其互质的个数为n-1
如果不是素数i%pj==0 phi[pj * i] = phi[i]p[j]
i%pj!=0 phi[pj * i] = ph[i]p[j]*(1-1/pj)
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e6+10;
int n;
int phi[N];
int primes[N], cnt;
bool st[N];
LL get_eulers(int n)
{
phi[1] = 1;
LL res = 0;
for( int i = 2; i <= n; i++ ){
if(!st[i]){
primes[cnt++] = i;
phi[i] = i-1;
}
for( int j = 0; primes[j] <= n/i; j++ ){
st[primes[j]*i] = true;
if(i%primes[j]==0){
phi[i*primes[j]] = phi[i]*primes[j];
break;
}
phi[i*primes[j]] = phi[i]*(primes[j]-1);
}
}
for( int i = 1; i <= n; i++ )
res+=phi[i];
return res;
}
int main()
{
cin>>n;
cout<<get_eulers(n)<<endl;
return 0;
}