BZOJ 2301: [HAOI2011]Problem b (Mobius inversion)

2301: [HAOI2011]Problem b

Time Limit: 50 Sec  Memory Limit: 256 MB
Submit: 7931  Solved: 3876
[Submit][Status][Discuss]

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.


 

Input

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

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

 

Sample Input

2

2 5 1 5 1

1 5 1 5 2


 

Sample Output


14

3


 

HINT

 



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

Thought: but it's the basic problem of Mobius inversion. See blog for details https://blog.csdn.net/huayunhualuo/article/details/51378405

Code:

#include<iostream>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<string>
#include<queue>
#include<vector>
#include<map>
#define ll long long
#define inf 0x3f3f3f3f3f3f3f3fLL
using namespace std;
const int maxn=1e5+10;
ll mu[maxn],pri[maxn];
ll a,b,c,d,k;
ll sum[maxn];
bool ok[maxn];
void init()
{
    mu[1]=sum[1]=1;
    ll cnt=0;
    for(ll i=2;i<maxn;i++)
    {
        if(!ok[i])
        {
            pri[cnt++]=i;
            mu[i]=-1;
        }
        for(ll j=0;j<cnt&&i*pri[j]<maxn;j++)
        {
            ok[i*pri[j]]=1;
            if(i%pri[j]) mu[i*pri[j]]=-mu[i];
            else
            {
                mu[i*pri[j]]=0;
                break;
            }
        }
        sum[i]=sum[i-1]+mu[i];
    }
}
ll jud(ll x,ll y)
{
    x/=k;y/=k;
    if(x>y) swap(x,y);
    ll ans=0;
    for(ll i=1,l=1;i<=x;i=l+1)
    {
        l=min(x/(x/i),y/(y/i));
        ans+=(sum[l]-sum[i-1])*(x/i)*(y/i);
    }
    return ans;
}
int main()
{
    int T,cas=1;
    init();
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld%lld%lld%lld%lld",&a,&b,&c,&d,&k);
        //printf("Case %d: ",cas++);
        if(!k)
        {
            printf("0\n");
            continue;
        }
        else
        {
            ll ans=jud(b,d)+jud(a-1,c-1)-jud(a-1,d)-jud(b,c-1);
            printf("%lld\n",ans);
        }
    }
    return 0;
}

 

Posted by piyushsharmajec on Sat, 30 Nov 2019 09:47:22 -0800