220. 最大公约数 欧拉函数 公式化简

题目

在这里插入图片描述

题解思路

首先化简成下面这样。
在这里插入图片描述
对于每个素数P都有一个1 N/P的区间让 a/p 和 b/p,我们只要算出区间内互质数的数对,枚举每个素数求和就是答案。
由欧拉函数可以求得1 到 N 中与N互质的数的个数 对其求前缀和 ,就是数对的一半了,这里a b 是可以交换的 。(当 a b 相等 为 p 的时候 就不能了)

参考文章

AC代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#include <map>
#include <string>
using namespace std;

const  int  INF =  0x3f3f3f3f;
const  int  N = 1e7 + 10 ;

bool st [ N ] ;
int  prm[ N ] ;
int  hi[ N ] ;
long long  sum[ N ] ;
int cnt = 1 ;

void in (int  n )
{
    cnt = 1 ;
    st[1] = 1 ;
    hi[1] = 1 ;
    for (int i = 2 ; i <= n ; i++ )
    {
        if ( ! st[i] )
        {
            prm[cnt] = i ;
            cnt++ ;
            hi[i] = i - 1 ;
        }
        for (int j = 1 ; i*prm[j] <= n ; j++ )
        {
            st[i*prm[j]] = 1 ;
            if ( i % prm[j] == 0 )
            {
                hi[i*prm[j]] = hi[i] * prm[j] ;
                break;
            }
            hi[ i*prm[j] ]  = hi[i] * ( prm[j] - 1 ) ;
        }
    }
}


int main ()
{
    ios::sync_with_stdio(false);
    int n ;
    cin >> n ;
    in(n);
    long long re = 0 ;
    for (int i = 1 ; i <= n ; i++ )
    {
        sum[i] = sum[ i-1 ] + hi[i] ;
    }
    for (int i = 1 ; i < cnt ; i++ )
    {
        int p = prm[i] ;
        re += 2*sum[ n / p ] - 1 ;
    }
    cout << re << "\n" ;
    return 0 ;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值