GCD 容斥原理

Problem Description

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.

Sample Input

2
1 3 1 5 1
1 11014 1 14409 9

Sample Output

Case 1: 9
Case 2: 736427

Hint

For the first sample input, all the 9 pairs of numbers are (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 5), (3, 4), (3, 5).
题意:从1--b和1--d两个集合中,一个集合中的元素为x,一个为y,GCD(x,y)=k,求这样的x,y一共有多少组
思路:
1.找到了一个数学规律,1--b/k集合1--d/k集合, 一个集合中的元素为x,一个为y,GCD(x,y)=1的组数和题目所求的一样。
2.题目附加条件 (x=5, y=7) and (x=7, y=5) 是一样的,所以在求解的时候要注意。
3.枚举x,求x与1--d/k中有多少个互素数(GCD(x,y)=1
#include <cstring>
#include <cstdio>
#include <iostream>
using namespace std;
typedef long long ll;
ll prime[1005];
int main()
{
    int icase=0,t;
    cin>>t;
    while(t--)
    {   ll a,b,c,d,k,sum,n,m;
        cin>>a>>b>>c>>d>>k;
        printf("Case %d: ",++icase);
        if(k==0||k>b||k>d)
        {
            printf("0\n");
            continue;
        }
        b=b/k;
        d=d/k;
        n=b<=d?b:d;//确保n<m
        m=b>=d?b:d;
        sum=m; //因为当n=1时 m全符合
        for(int i=2;i<=n;i++)
        {

          int  x=i;
          int  cnt=0;
            memset(prime,0,sizeof(prime)); //初始化数组
            for(int j=2;j*j<=x;j++)   //求得x的素因子数组
            {
                if(x%j==0)
                {
                    prime[cnt++]=j;
                    while(x%j==0)
                        x=x/j;
                }
            }
            if(x>1)
                prime[cnt++]=x;

            sum=sum+m-i; //考虑 n>m的部分后m的大小
            for(ll j=1;j<(1<<cnt);j++)
            {
                ll res=1,flag=0;
                for(int k=0;k<cnt;k++)
                {
                    if(j&(1<<k))
                    {
                        flag++;
                        res=res*prime[k];
                    }
                }
                res=m/res-i/res;  //考虑 n>m的部分符合的个数
                if(flag&1)
                    sum=sum-res;
                else
                    sum=sum+res;
            }
        }
        printf("%lld\n",sum);
    }
    return 0;
}
做了2道题目之后感觉容斥原理打个模板往里面套就可以了,只是细节需要处理

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值