ACM学习历程—HDU1695 GCD(容斥原理 || 莫比乌斯)

时间:2023-12-04 19:24:26

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

题目大意就是求x在[a, b],y在[c, d]区间内的满足gcd(x, y) == k的(x, y)对有多少,而且(3, 4) == (4, 3)这种。

可以使用容斥原理来做。

也可以使用莫比乌斯反演。

设F(d)表示满足区间的(x, y),且d | gcd(x, y)的个数。

f(d)表示满足区间的(x, y), 且d == gcd(x, y)的个数。

那么F(d)
= sum(f(n)) (d|n)

然后根据莫比乌斯反演:

F(d) =
sum(f(n)) (d|n) => f(d) = sum(u(n/d)*F(n)) (d|n)

然后目标就是求F(n)了。

首先不计重复对的话,总共有(b/n)*(d/n)对。

然后需要排除重复的,重复的不外乎是(a, b) == (b, a)这种情况。而且这种情况都且出现两次。

而且需要减掉(a, a)的情况(强行让b <= d),于是就是:(b/n)*(b/n) – (b/n)

然后除二就是多加的,于是:

F(n) = (b/n)*(d/n)-((b/n)*(b/n)-(b/n))/2

代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <set>
#include <map>
#include <queue>
#include <string>
#define LL long long using namespace std; const int maxN = ;
int u[maxN], prime[maxN];
bool vis[maxN];
int a, b, c, d, k; //莫比乌斯反演
//F(n)和f(n)是定义在非负整数集合上的两个函数
//并且满足条件F(n) = sum(f(d)) (d|n)
//那么f(n) = sum(u(d)*F(n/d)) (d|n)
//case 1: if d = 1, u(d) = 1
//case 2: if d = p1*p2...pk, (pi均为互异素数), u(d) = (-1)^k
//case 3: else, u(d) = 0;
//性质1: sum(u(d)) (d|n) = 1 (n == 1) or 0 (n > 1)
//性质2: sum(u(d)/d) (d|n) = phi(n)/n
//另一种形式:F(d) = sum(f(n)) (d|n) => f(d) = sum(u(n/d)*F(n)) (d|n)
//线性筛选求莫比乌斯反演函数代码
void mobius()
{
memset(vis, false,sizeof(vis));
u[] = ;
int cnt = ;
for(int i = ; i < maxN; i++)
{
if(!vis[i])
{
prime[cnt++] = i;
u[i] = -;
}
for(int j = ; j < cnt && i*prime[j] < maxN; j++)
{
vis[i*prime[j]] = true;
if(i%prime[j])
u[i*prime[j]] = -u[i];
else
{
u[i*prime[j]] = ;
break;
}
}
}
} void work()
{
if (k == )
{
printf("0\n");
return;
}
LL ans = ;
if (b > d)
swap(b, d);
for (LL i = k; i <= b; i += k)
ans += ((b/i)*(d/i)-((b/i)*(b/i)-(b/i))/)*u[i/k];
printf("%I64d\n", ans);
} int main()
{
//freopen("test.in", "r", stdin);
mobius();
int T;
scanf("%d", &T);
for (int times = ; times <= T; ++times)
{
printf("Case %d: ", times);
scanf("%d%d%d%d%d", &a, &b, &c, &d, &k);
work();
}
return ;
}