【容斥原理】HDOJ GCD 1695



GCD

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7783    Accepted Submission(s): 2891


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).
 

Source
 

Recommend
wangye   |   We have carefully selected several similar problems for you:  1689 1690 1693 1691 1698 
 


題意:

給定k,x,y,求 1<=a<=x 1<=b<=y 中滿足 gcd(a,b)=k 的(a,b)對數。

解題思路:

容斥原理,具體講解推薦一篇文章:點擊打開鏈接

AC代碼:

#include <stdio.h>
#include <string.h>
#include <algorithm>

using namespace std;

const int MAXN=100010;

typedef long long LL;

LL E[MAXN];
LL num[MAXN];
LL Prime[MAXN][10];

void euler()
{
    E[1]=1;
    for(int i=2;i<MAXN;i++){
        E[i]=i;
    }
    for(int i=2;i<MAXN;i++){
        if(E[i]==i){
            for(int j=i;j<MAXN;j+=i){
                E[j]=E[j]/i*(i-1);
                Prime[j][num[j]++]=i;
            }
        }
    }
    for(int i=2;i<MAXN;i++){
        E[i]+=E[i-1];
    }
}

//DFS求解不大於b的數中與n互質的數
LL DFS(int x,int b,int n)
{
    LL res=0;
    for(int i=x;i<num[n];i++)
        res+=b/Prime[n][i]-DFS(i+1,b/Prime[n][i],n);//奇加偶減
    return res;
}

int main()
{
    int t;
    int xp=1;
    scanf("%d",&t);
    euler();
    while(t--){
        LL a,b,c,d,k;
        scanf("%lld%lld%lld%lld%lld",&a,&b,&c,&d,&k);
        printf("Case %d: ",xp++);
        if(k==0){
            printf("0\n");
            continue;
        }
        if(b>d){
            swap(b,d);
        }
        b/=k;
        d/=k;
        LL res=E[b];
        for(int i=b+1;i<=d;i++)
            res+=b-DFS(0,b,i);
        printf("%lld\n",res);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章