欧拉函数:计算1~N中与N互质的数的个数

欧拉函数定义:对于所有的 a,b a , b ,若 gcd(a,b)=1 g c d ( a , b ) = 1 ,则称 a,b a , b 互质。

计算方式: [1,N] [ 1 , N ] 中与 N N 互质的数的个数被称为欧拉函数,记为 ϕ(N)

int phi(int n) {
    int ans = n;
    for (int i = 2; i <= sqrt(n); ++i) if (n % i == 0) {
        ans = ans / i * (i-1);
        while (n % i == 0) n /= i;
    }
    if (n > 1) ans = ans / n * (n-1);
    return ans;
}

以下的代码以 O(NlogN) O ( N l o g N ) 复杂度求出 [2,N] [ 2 , N ] 中每个数的欧拉函数。

void euler(int n) {
    for (int i = 2; i <= n; ++i) phi[i] = i;
    for (int i = 2; i <= n; ++i) if (phi[i] == i)
        for (int j = i; j <= n; j += i)
            phi[j] = phi[j] / i * (i-1);
}

下面是黄学长的代码,利用线性筛法的思想在 O(N) O ( N ) 的时间内快速递推出 [2,N] [ 2 , N ] 中每个数的欧拉函数。

typedef long long ll;
const int maxn = 10000000 + 5;
int phi[maxn], pri[1000005], n, tot;
bool mark[maxn];
ll ans, sum[maxn];
void getphi() {
    phi[1] = 1;
    for (int i = 2; i <= n; i++) {
        if (!mark[i]) { phi[i] = i - 1; pri[++tot] = i; }
        for (int j = 1; j <= tot; j++) {
            int x = pri[j];
            if (i*x>n)break;
            mark[i*x] = 1;
            if (i%x == 0) { phi[i*x] = phi[i] * x; break; }
            else phi[i*x] = phi[i] * phi[x];
        }
    }
}

BZOJ2818

给定整数N,求 1x,yN 1 ≤ x , y ≤ N Gcd(x,y) G c d ( x , y ) 为素数的数对 (x,y) ( x , y ) 有多少对.

#define N 10000005
using namespace std;
int n,p,tot;
int phi[N],pri[1000005];
bool mark[N];
ll ans,sum[N];
void getphi() {
    phi[1]=1;
    for(int i=2;i<=n;i++) {
        if(!mark[i]){phi[i]=i-1;pri[++tot]=i;}
        for(int j=1;j<=tot;j++) {
            int x=pri[j];
            if(i*x>n)break;
            mark[i*x]=1;
            if(i%x==0){phi[i*x]=phi[i]*x;break;}
            else phi[i*x]=phi[i]*phi[x];
        }
    }
}
int main() {
    scanf("%d",&n);
    getphi();
    for(int i=1;i<=n;i++)
        sum[i]=sum[i-1]+phi[i];
    for(int i=1;i<=tot;i++)
        ans+=sum[n/pri[i]]*2-1;
    printf("%lld",ans);
    return 0;
}
  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值