GCD HDU - 1695
Give n 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
思路: 莫比乌斯反演 点击打开链接 莫比乌斯讲解;
设 f[i] 为 gcd( a,b) = i 的个数 F[i] 为 gcd( a,b) =i*k 的个数 (即 等于 i 的倍数的个数)
显然 F[i] = floor(b/i)* floor(m/d) ( floor 向下取整)
反演 :
即
然后就是去重问题了,由于<a,b>,<b,a> 算一个,去重只需要考虑 小区间的那个就行。
具体的解答上面的那个 ppt 中有个类似的例题。
由于这题数据比较水,不需要考虑分块以及维护前缀和。(但是还是会爆int)
#pragma comment(linker, "/STACK:1024000000,1024000000")
//#include <bits/stdc++.h>
#include<string>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<algorithm>
#define maxn 100100
#define INF 0x3f3f3f3f
#define eps 1e-8
#define MOD 1000000007
#define ll __int64
using namespace std;
int mu[maxn];
void mul()
{
for(int i=1;i<maxn;i++)
{
int ta=i==1?1:0;
int de=ta-mu[i];
mu[i]=de;
for(int j=i*2;j<maxn;j+=i)
mu[j]+=de;
}
}
int main()
{
mul();
int T;
int kase=1;
scanf("%d",&T);
int a,b,c,d,k;
while(T--)
{
scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);
printf("Case %d: ",kase++);
if(k==0) {puts("0"); continue; }
b/=k;
d/=k;
if(b>d) swap(b,d);
ll ans1=0;
for(int i=1;i<=b;i++)
{
ans1+=(ll)mu[i]*(b/i)*(d/i);
}
ll ans2=0;
for(int i=1;i<=b;i++)
{
ans2+=(ll)mu[i]*(b/i)*(b/i);
}
printf("%I64d\n",ans1-ans2/2);
}
return 0;
}
还有一种 容斥+欧拉函数的做法。
思路就是 枚举 a 找到区间2 中gcd(a ,x) ==1 的个数, 同样需要去重。