Luogu P2522 [HAOI2011]Problem b

Keywords: C++

Title Description

For the given n queries, how many pairs of numbers (x,y) can be found each time, a ≤ x ≤ b, c ≤ y ≤ d, and gcd(x,y) = k, gcd(x,y) function is the greatest common divisor of X and y.

I / O format

Input format:

 

The first line is a n integer n, a n d the next N lines are five integers representing a, b, c, D and k respectively

 

Output format:

 

There are n lines in total. An integer in each line indicates the number of pairs (x,y) that meet the requirements

 

Example of input and output

Input example ා 1:copy
2
2 5 1 5 1
1 5 1 5 2
Output example:copy
14
3

Explain

100% of the data meet the following requirements: 1 ≤ n ≤ 50000, 1 ≤ a ≤ b ≤ 50000, 1 ≤ c ≤ d ≤ 50000, 1 ≤ k ≤ 50000

 

 

Mobius inversion

First of all, you need to ask $\ sum ^ {n} {I = 1} \ sum ^ {m} {I = 1} \ left [\ GCD \ left (I, J \ right) = 1 \ right]$

Then it's not hard to find that this problem can be treated with tolerance and exclusion

Suppose $work (I, J) = \ sum ^ {n} {I = 1} \ sum ^ {m} {I = 1} \ left [\ GCD \ left (I, J \ right) = 1 \ right]$

Then $ans=work(b,d)-work(a-1,d)-work(c-1,b)+work(a-1,c-1)$

// luogu-judger-enable-o2
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int MAXN=1e6+10;
inline int read()
{
    char c=getchar();int x=0,f=1;
    while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    return x*f;
}
int N,a,b,c,d,k,ans;
int vis[MAXN],prime[MAXN],mu[MAXN],tot=0;
void GetMu()
{
    vis[1]=1;mu[1]=1;
    for(int i=2;i<=N;i++)
    {
        if(!vis[i]) prime[++tot]=i,mu[i]=-1;
        for(int j=1;j<=tot&&i*prime[j]<=N;j++)
        {
            vis[i*prime[j]]=1;
            if(i%prime[j]==0) {mu[i*prime[j]]=0;break;}
            else mu[i*prime[j]]=-mu[i];
        }
    }
    
    for(int i=1;i<=N;i++) 
        mu[i]+=mu[i-1];
}
int work(int n,int m)
{
    int limit=min(n/k,m/k),ans=0;
    for(int i=1,nxt;i<=limit;i=nxt+1)
    {
        nxt=min(n/(n/i),m/(m/i));
        ans+=(mu[nxt]-mu[i-1])*(n/(k*i))*(m/(k*i));
    }
    return ans;
}
main()
{
    N=1e5;
    GetMu();
    int QWQ=read();
    while(QWQ--)
    {
        a=read(),b=read(),c=read(),d=read(),k=read();
        ans=work(b,d)-work(a-1,d)-work(c-1,b)+work(a-1,c-1);
        printf("%d\n",ans);        
    }
    return 0;
} 

Posted by basheer12m on Thu, 02 Apr 2020 21:55:19 -0700