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).
题意
求1~n与1~m中gcd为k的个数
题解:
gcd(n,m)=k 等价于 gcd(n/k,m/k)=1
令b/=k,d/=k;
即求1~b与1~d之间互质的个数
求出b d 的最大值 交换d为最大值
那么1~b范围内可以直接用欧拉函数求
剩下的即 1~b与b+1~d互质的个数
然后用容斥原理 枚举b+1~d 每个数与b容斥
可以在预处理欧拉函数线性筛的时候预处理每个数的质因子
AC代码
#include <cstdio>
#include <cmath>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
const int N = 1e5+10;
int phi[N],prime[N];
vector<int> yinz[N];
int tot = 0;
void init(){
phi[1] = 1;
for (int i = 2; i < N; ++i){
if (!phi[i]){
phi[i] = i-1;
prime[tot++] = i;
}
for (int j = 0; j < tot&&1ll*i*prime[j]<N; ++j){
if (i%prime[j]) phi[i*prime[j]] = phi[i]*(prime[j]-1);
else {
phi[i*prime[j]] = phi[i]*prime[j];
break; //加break目的 往下循环会计算到 如4*3 和6*2
}
}
}
for (int i = 1; i < 100000; ++i){
int tmp = i;
for (int j = 0; (LL)prime[j]*prime[j]<=tmp; ++j){
if (tmp%prime[j] == 0){
yinz[i].push_back(prime[j]);
tmp/=prime[j];
while (tmp%prime[j] == 0){
tmp/=prime[j];
}
}if (tmp==1) break;
}
if (tmp>1) yinz[i].push_back(tmp);
}
}
LL dfs(LL x,LL b,LL now){
LL res = 0;
for (LL i = x; i < yinz[now].size(); ++i){
res += b/yinz[now][i]-dfs(i+1,b/yinz[now][i],now);
}
return res;
}
int main(){
init();
int t;
scanf("%d",&t);
int cse = 1;
while (t--){
LL a,b,c,d,k;
scanf("%lld%lld%lld%lld%lld",&a,&b,&c,&d,&k);
if(k==0||k>b||k>d)
{
printf("Case %d: 0\n",cse++);
continue;
}
printf("Case %d: ",cse++);
if (b>d) swap(b,d);
b/=k,d/=k;
LL ans = 0;
for (LL i = 1; i <= b; ++i){
ans += phi[i];
}
for (LL i = b+1; i <= d; ++i){
ans += b-dfs(0,b,i);
}
printf("%lld\n",ans);
}
return 0;
}