【容斥原理】HDOJ GCD 1695

来源:互联网 发布:淘宝处罚规则 编辑:程序博客网 时间:2024/06/05 20:50



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
21 3 1 5 11 11014 1 14409 9
 

Sample Output
Case 1: 9Case 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
2008 “Sunline Cup” National Invitational Contest
 

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


0 0
原创粉丝点击