[HDU 1695]GCD

【问题描述】

  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.

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

【输入】

  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.

【输出】

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

【算法分析】

  莫比乌斯反演。

【程序代码】

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<algorithm>
 5 using namespace std;
 6 typedef long long ll;
 7 const ll maxn=100010;
 8 ll prime[maxn],mu[maxn],phi[maxn],t,n,a,b,c,d,k,minn;
 9 ll ans;
10 bool vis[maxn];
11 void getmu(){
12     int cnt=0;
13     mu[1]=1; 
14     for (int i=2;i<=maxn;i++){
15         if (!vis[i]){
16             prime[cnt++]=i;
17             mu[i]=-1;
18             phi[i]=i-1;
19         }
20         for (int j=0;j<cnt&&prime[j]*i<=maxn;j++){
21             vis[prime[j]*i]=1;
22             if (i%prime[j]){
23                 mu[i*prime[j]]=-mu[i];
24                 phi[i*prime[j]]=phi[i]*(prime[j]-1);
25             }
26             else {
27                 mu[i*prime[j]]=0;
28                 phi[i*prime[j]]=phi[i]*prime[j];
29                 break;
30             }
31         }
32     }
33 }
34 int main(){
35     memset(vis,0,sizeof(vis));
36     getmu();
37     scanf("%d",&t);
38     for (int l=1;l<=t;l++){
39         scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);
40         if (k==0){
41             printf("Case %d: 0\n",l);
42             continue;
43         }
44         b/=k; d/=k; ans=0; minn=min(b,d);
45         for (int i=1;i<=minn;i++){
46             ans+=mu[i]*(b/i)*(d/i)-phi[i];
47         }
48         printf("Case %d: ",l);
49         cout<<ans<<endl;
50     }
51     return 0;
52 }
View Code

声明:本文为博主原创文章,未经允许请勿转载。

posted on 2016-04-24 11:31  Double680  阅读(144)  评论(0编辑  收藏  举报

导航