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
分析
这个题的题意就是说给你两个区间,求有多少对(x,y),x从第一个区间中选,y从第二个区间中选,使得gcd(x,y) = k,这个题的话简化一下把a,b,c,d都除以k,那么就是咱们要求的范围了,但是这个输入的话听别人说是左边界默认为1,说是从题意里读出来的,属实是咱这英语水平不太行了哈哈哈,下面请看莫比乌斯反演解题的推理
总结
当某个函数不易求得,但他的约数的函数值之和容易求或者倍数的函数值之和容易求的时候可以考虑莫比乌斯反演
代码
#include<iostream>
using namespace std;
const int N = 100010;
typedef long long LL;
int mobius[N],primes[N],cnt;
bool st[N];
void init(int n){
mobius[1] = 1;
for(int i=2;i<=n;i++){
if(!st[i]){
primes[cnt++] = i;
mobius[i] = -1;
}
for(int j=0;j<cnt && primes[j]*i <= n;j++){
int t = i * primes[j];
st[t] = true;
if(i % primes[j] == 0){
mobius[t] = 0;
break;
}
mobius[t] = -mobius[i];
}
}
}
LL solve(LL a,LL b){
LL ans = 0;
LL minn = min(a,b);
for(LL i=1;i<=minn;i++){
ans += mobius[(int)i] * (a/i) * (b/i);
}
return ans;
}
int main(){
init(N-1);
int T;
cin>>T;
for(int i=1;i<=T;i++){
cout<<"Case "<<i<<": ";
LL a,b,c,d,k;
cin>>a>>b>>c>>d>>k;
if(k == 0){//这是个坑,注意别踩进去哈哈哈
printf("0\n",i);
continue;
}
b /= k;
d /= k;
LL ans = 0;
if(b > d) swap(b,d);
ans += solve(b,d);
ans -= solve(b,b)/2;
cout<<ans<<endl;
}
return 0;
}