HDU 1695 GCD

GCD

Time Limit: 3000ms
Memory Limit: 32768KB
This problem will be judged on HDU. Original ID: 1695
64-bit integer IO format: %I64d      Java class name: Main
 
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

 
解题:容斥 + 数论
 

x是[1,b],y是[1,d],求GCD(x,y)=k的对数(x,y无序)

对x,y都除以k,则求GCD(x,y)=1

此时枚举x,问题转化为[1,d]区间内与x互素的数字个数,这个问题是hdu 4135

有一个特殊的地方是x,y无序,对于这点只要保证x始终小于y就可以了

特判k=0

 

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long LL;
 4 int b,d,k;
 5 vector<LL>g;
 6 int main() {
 7     int kase,cs = 1;
 8     scanf("%d",&kase);
 9     while(kase--) {
10         scanf("%*d%d%*d%d%d",&b,&d,&k);
11         if(!k) {
12             printf("Case %d: 0\n",cs++);
13             continue;
14         }
15         b /= k;
16         d /= k;
17         if(b > d) swap(b,d);
18         LL ret = 0;
19         for(int i = 1,tmp; i <= b; ++i) {
20             g.clear();
21             tmp = i;
22             for(int j = 2; j*j <= tmp; ++j) {
23                 if(tmp%j == 0) {
24                     while(tmp%j == 0) tmp /= j;
25                     for(int k = g.size()-1; k >= 0; --k)
26                         if(abs(g[k]*j) <= d) g.push_back(-j*g[k]);
27                     g.push_back(j);
28                 }
29             }
30             if(tmp > 1) {
31                 for(int k = g.size()-1; k >= 0; --k)
32                     if(abs(g[k]*tmp) <= d) g.push_back(-tmp*g[k]);
33                 g.push_back(tmp);
34             }
35             LL ans = 0;
36             for(int j = g.size()-1; j >= 0; --j) ans += d/g[j] - (i-1)/g[j];
37             ret += (d - i + 1) - ans;
38         }
39         printf("Case %d: %I64d\n",cs++,ret);
40     }
41     return 0;
42 }
View Code

 

posted @ 2015-09-11 20:44  狂徒归来  阅读(170)  评论(0编辑  收藏  举报