【HDU-1695】GCD 反演模板题+去重

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

烫脚中文题意

 求满足$a\leq x\leq b,c\leq y\leq d$,且$x$可以等于$y$,满足$gcd(i,j)=k$有多少对$x$,$y$。

思路

原题意已经满足了$a= = 1$并且$c= = 1$。

手头上模板能求$\sum_{i=1}^{n}\sum_{j=1}^{m}[gcd(i,j)=k]$.

不妨令$b\leq d$。

先求$\sum_{i=1}^{b}\sum_{j=1}^{d}[gcd(i,j)=k]$,再减去$\sum_{i=1}^{b}\sum_{j=1}^{b}[gcd(i,j)=k]$去重。

AC代码

 1 #include<bits/stdc++.h>
 2 #define ll long long
 3 using namespace std;
 4 const int SIZE=1e6+10;
 5 bool check[SIZE];
 6 int prime[SIZE];
 7 int mu[SIZE];
 8 void Moblus(){
 9     memset(check,false,sizeof(check));
10     mu[1]=1;
11     int tot=0;
12     for(int i=2;i<=SIZE;i++){
13         if(!check[i]){
14             prime[tot++]=i;
15             mu[i]=-1;
16         }
17         for(int j=0;j<tot;j++){
18             if(i*prime[j]>SIZE){
19                 break;
20             }
21             check[i*prime[j]]=true;
22             if(i%prime[j]==0){
23                 mu[i*prime[j]]=0;
24                 break;
25             }
26             else{
27                 mu[i*prime[j]]=-mu[i];
28             }
29         }
30     }
31 }
32 
33 ll sum(int x,int y,int k){
34     ll res=0;
35     int minn=min( floor(x/k) , floor(y/k) ); 
36     for(int d=1;d<=minn;d++){
37         res += (ll)mu[d]*(ll)floor( x/(d*k) )*(ll)floor( y/(d*k) );
38     }
39     return res;
40 }
41 
42 int main(){
43     Moblus();
44     int t;scanf("%d",&t);
45     int kase=1;
46     while(t--){
47         int a,b,c,d,e;scanf("%d%d%d%d%d",&a,&b,&c,&d,&e);
48         if(!e){//注意判断0,之前Error了好几发……
49             printf("Case %d: 0\n",kase++);continue;
50         }
51         if(b>d)swap(b,d);//不交换会WA
52         ll ans1=sum(b,d,e);
53         ll ans2=sum(b,b,e);
54         printf("Case %d: %lld\n",kase++,ans1-ans2/2);
55     }
56 }

故事会

shk001:今天上的数论,又归我管,你们又迫害我。

tudouuuuu:Rea1的数链剖分还没写完呢。

shk001:行⑧,我背数论、数学、计算几何、dp、搜索的锅,怎么感觉这几天全是我的锅。

(*tudouuuuu去普陀山玩)

tudouuuuu:我打赌输了,我写10道反演,行⑧!

猜你喜欢

转载自www.cnblogs.com/tudouuuuu/p/11600308.html