GCD
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 15656 Accepted Submission(s): 6024
Problem 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).
Source
2008 “Sunline Cup” National Invitational Contest
Recommend
wangye | We have carefully selected several similar problems for you: 1689 1693 1691 1692 1697
#include<bits/stdc++.h>
using namespace std;
#define debug puts("YES");
#define rep(x,y,z) for(int (x)=(y);(x)<(z);(x)++)
#define read(x,y) scanf("%d%d",&x,&y)
#define ll long long
/*
题目大意:给定两个区间,
计数其gcd(i,j)=k的对数,要求对数不相同的条件是数字不相同,而不是顺序。
这道题用容斥来解的话有点费脑筋,
但还是可以求解的。
首先压缩区间,b/=k,d/=k;这样就
转换成了求gcd(i,j)=1的对数。
对2到b区间,遍历,然后求出在d上界的控制下,互质的个数,
当然要去除重复的个数,这里利用gcd(x,i)=gcd(x,x+i)的性质,
就可以像b-i这样放缩上界,然后DFS容斥计数。
*/
const int maxn =2e5+5;
int a,b,c,d,k;
ll ans;
vector<int> zs[maxn];
void init()
{
int vis[maxn];memset(vis,0,sizeof(vis));
for(int i=2;i<maxn;i++) if(!vis[i])
for(int j=i;j<maxn;j+=i)
{
zs[j].push_back(i);
vis[j]=1;
}
}
void dfs(int loc,int pos,int cnt,int num,int ub)
{
if(pos>=zs[loc].size()) return ;
if(cnt&1) ans+=ub-ub/num;
else ans-=ub-ub/num;
for(int i=pos+1;i<zs[loc].size();i++)
dfs(loc,i,cnt+1,num*zs[loc][i],ub);///枚举的思维是:下一个选什么
}
int main()
{
init();
int t;scanf("%d",&t);
for(int ca=1;ca<=t;ca++)
{
scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);
if(k==0) {printf("Case %d: %lld\n",ca,0LL);continue;}///要转类型,不然爆出大数字
if(b>d) swap(b,d);
b/=k,d/=k,ans=0;
if(b) ans+=d;
for(int i=2;i<=b;i++) for(int j=0;j<zs[i].size();j++) dfs(i,j,1,zs[i][j],d-i);///利用了一个性质,gcd(x,i)=gcd(x,x+i)
///很巧妙的利用数论性质来进行上界的压缩。
printf("Case %d: %lld\n",ca,ans);
}
return 0;
}