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

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

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

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

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

#include 

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<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;
}

 

你可能感兴趣的:(acm,数论)