loj 528「LibreOJ β Round #4」求和

题目链接:https://loj.ac/problem/528

题意:\sum_{i=1}^{N}\sum_{j=1}^{M}\mu ^{2}\left ( gcd\left ( i,j \right ) \right )

思路:转自官方题解:题目要求的即是多少对数的最大公约数满足每个质因子不拥有超过1个。定义 f(x) 表示有多少对数的最大公约数含有 x^{2}这个因子,显然

f(x) = \lfloor \frac{n}{x^2} \rfloor \cdot \lfloor \frac{m}{x^2} \rfloor

我们只要减去所有不合法的数字就能得到答案,但是一对数字的最大公约数如果含有多个平方质因子的话,会被重复计算。容易发现只要用 \mu作容斥系数就能得到答案,即

\mu(x) \cdot \lfloor \frac{n}{x^2} \rfloor \cdot \lfloor \frac{m}{x^2} \rfloor

因为至少要除掉x^{2}所以x只需要枚举到 \sqrt{n}。时间复杂度O(\sqrt{n})

#pragma comment(linker, "/STACK:102400000,102400000")
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define lson root<<1,l,mid
#define rson root<<1|1,mid+1,r
#define Key_Value ch[ch[root][1]][0]
#define DBN1(a)           cerr<<#a<<"="<<(a)<<"\n"
#define DBN2(a,b)         cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<"\n"
#define DBN3(a,b,c)       cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<"\n"
#define DBN4(a,b,c,d)     cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<"\n"
#define DBN5(a,b,c,d,e)   cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<", "<<#e<<"="<<(e)<<"\n"
#define DBN6(a,b,c,d,e,f) cerr<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<", "<<#e<<"="<<(e)<<", "<<#f<<"="<<(f)<<"\n"
#define clr(a,x) memset(a,x,sizeof(a))
using namespace std;
typedef long long ll;
const int maxn=1e7+5;
const int INF=0x3f3f3f3f;
const ll P=998244353LL;
const double PI=acos(-1.0);
template<typename T>
inline T read(T&x){
    x=0;int _f=0;char ch=getchar();
    while(ch<'0'||ch>'9')_f|=(ch=='-'),ch=getchar();
    while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
    return x=_f?-x:x;
}
inline ll add(ll a,ll b){return (a+=b)>=P?a-P:a;}
inline int sub(int a,int b){return (a-=b)<0?a+P:a;}
inline ll mul(ll a,ll b){return (a%P)*(b%P)%P;}
bool isPrime[maxn];
ll n,m;
int mu[maxn],primes[maxn];
void sieve(int mx){
    int num=0;
    mu[1]=1;
    for (int i=2;i<=mx;i++){
        if (!isPrime[i]){primes[num++]=i;mu[i]=-1;}
        static int d;
        for (int j=0;j<num && (d=i*primes[j])<=mx;j++){
            isPrime[d]=true;
            if (i%primes[j]==0){
                mu[d]=0;
                break;
            }
            else mu[d]=-mu[i];
        }
    }
}
int main(){
    read(n),read(m);
    int mx=(int)sqrt(min(n,m)*1.0);
    sieve(mx);
    ll ans=mul(n,m);
    for (int i=2;i<=mx;i++){
        ans=add(ans,mul(mul(1LL*mu[i],n/i/i),m/i/i));
        if (ans<0) ans+=P;
    }
    printf("%lld\n",ans);
    return 0;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注