莫比乌斯反演 1004 BZOJ 2301

题意:
对于给出的 n 个询问,每次求有多少个数对 (x,y) ,
满足 a ≤ x ≤ b , c ≤ y ≤ d ,且 gcd(x,y) = k ,
gcd(x,y) 函数为 x 和 y 的最大公约数。
思路:
Ans(a~b,c~d)=Ans(b,d)-Ans(a-1,d)-Ans(b,c-1)+Ans(a-1,c-1)
求gcd(x,y)==k&& x<=n&&y<=m == gcd(x,y)==1 && x<=n/k && y<=m/k
这样会比直接求gcd(x,y)==k快上一倍

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<queue>
#include<stack>
#include<string>
#include<vector>
#include<map>
#include<set>
using namespace std;
#define lowbit(x) (x&(-x))
typedef long long LL;
const int maxn = 1000005;
const int inf=(1<<28)-1;
#define maxp 100005
bool notprimes[maxp];
int primes[maxp];
int mu[maxp];
void get_mu()
{
    memset(notprimes,false,sizeof(notprimes));
    primes[0]=0;
    mu[1]=1;
    for(int i=2;i<maxp;++i)
    {
        if(!notprimes[i])
        {
            primes[++primes[0]]=i;
            mu[i]=-1;
        }
        for(int j=1;j<=primes[0];++j)
        {
            if((LL)primes[j]*i>=maxp) break;
            notprimes[i*primes[j]]=true;
            if(i%primes[j])
            {
                mu[i*primes[j]]=-mu[i];
            }
            else
            {
                mu[i*primes[j]]=0;
                break;//代表i不是素数,mu[i*primes[j]]必然是0 
            }
        }
    }
}

LL Pre[maxp];
int k;

LL solve(int n,int m)
{
    n/=k,m/=k;
    LL Ans=0;
    int t=min(n,m),last;
    for(int i=1;i<=t;i=last+1)
    {
        last=min(n/(n/i),m/(m/i));
        Ans+=(LL)(Pre[last]-Pre[i-1])*(n/i)*(m/i);
    }
    return Ans;
}

int main()
{
    get_mu();
    Pre[0]=0;
    for(int i=1;i<maxp;++i)
        Pre[i]=Pre[i-1]+mu[i];
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int a,b,c,d;
        scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);
        LL Ans=solve(b,d)-solve(a-1,d)-solve(b,c-1)+solve(a-1,c-1);
        printf("%lld\n",Ans);
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值