hdu 1695 (容斥原理)

Given 5 integers: a, b, c, d, k, you're to find x in a...b, y in c...d that GCD(x, y) = k. GCD(x, y) means the greatest common divisor of x and y. Since the number of choices may be very large, you're only required to output the total number of different number pairs. 
Please notice that, (x=5, y=7) and (x=7, y=5) are considered to be the same. 

Yoiu can assume that a = c = 1 in all test cases. 

Input

The input consists of several test cases. The first line of the input is the number of the cases. There are no more than 3,000 cases. 
Each case contains five integers: a, b, c, d, k, 0 < a <= b <= 100,000, 0 < c <= d <= 100,000, 0 <= k <= 100,000, as described above. 

Output

For each test case, print the number of choices. Use the format in the example. 

题意:

在a~b,c~d这两个区间内找x,y,使得GCD(x,y)==k,题目又说a==c==1(真的无语,那还要输入a,b干嘛)

解题思路:

因为GCD(x,y)==k,所以GCD(x/k,y/k)==1

这样问题就转变为了求x/k和y/k互质的对数了,所以区间就可以缩小为1~b/k和1~d/k,所求的就是这两个区间里面互质数的对数了。(感觉网上很多都没把这一步讲明白,都是直接除以k)

假设b<d,(不满足则交换),然后分两个部分1~b和b+1~d

在1~b中使用容斥定理,会出现(1,2)和(2,1)两种情况,(所以要分成两个区间),枚举1~b的每一个数,用容斥定理计算,ans最后除以2;(这里也可以用欧拉函数计算,但是感觉代码量要大点,干脆都用容斥定理)

在b+1~d中就不会出现重复对数了,因为b+1已经大于b了,所以也是枚举然后直接加上

最后注意一下特判k==0时即可

小结:这种题目,看懂题目然后整理好思路,模板一套,处理好接口和数据范围,就不难了(虽然对我来说还是有点难...OvO...)下次试一下莫比乌斯反演来写

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

int fac[100000];
int div(int n)
{
    int cnt=0;
    for(int i=2;i*i<=n;i++)
    {
        if(n%i==0)
        {
            fac[cnt++]=i;
            while(n%i==0) n/=i;
        }
    }
    if(n>1) fac[cnt++]=n;
    return cnt;//素数因子的个数
}
int solve(int cnt,int n)//容斥原理
{
    int ans=0;
    for(int i=1;i< (1<<cnt) ; i++)
    {
        int ones=0,mult=1;
        for(int j=0;j<cnt;j++)
        {
            if(i & (1<<j))
            {
                ones++;
                mult*=fac[j];
            }
        }
        if(ones&1)//奇数加,偶数减
            ans+= n/mult;
        else
            ans-= n/mult;
    }
    return n-ans;
}
int main()
{
    int t,cs=1;
    scanf("%d",&t);
    while(t--)
    {
        int a,b,c,d,k;
        scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);
        if(k==0) {printf("Case %d: 0\n",cs++);continue;}//k==0特判
        if(b>d) swap(b,d);
        d/=k,b/=k;
        ll ans=0;
        for(int i=1;i<=b;i++)//1~b区间
        {
            int cnt=div(i);
            ans+=solve(cnt,b);
        }
        ans=(ans+1)/2;
        for(int i=b+1;i<=d;i++)//b+1~d区间
        {
            int cnt=div(i);
            ans+=solve(cnt,b);
        }
       printf("Case %d: %lld\n",cs++,ans);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值