Time Limit : 6000/3000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other)
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
题意:在[1,b]和[1,d]中找到x,y与k不互质的(x,y)的对数,(1,2) (2,1)只算一对
分析:把x,y,k都除以k后,即b,d除以k求[1,b/k]的x’和[1,d/k]的y’区间内互质的个数,b/k和d/k一定有一个较小或者相同,假定b/k较小
可以利用欧拉函数求[1,b/k]的的互质的个数,然后求[b/k+1,d/k+1]与[1,b/k]互质的个数,运用容斥定理来求。 当然也可以不用欧拉函数,应该时间不会超限, 不用欧拉函数可以参考:http://blog.csdn.net/feng_zhiyu/article/details/76222161
这里的思路
代码如下:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<vector>a
using namespace std;
typedef long long LL;
const int N=1e5+10;
int a,b,c,d,k;
LL primes[N],A[N],phi[N];
void Phi()///欧拉函数 实现记忆化以免时间超限
{
memset(A,0,sizeof(A));
A[0]=A[1]=1;
for(int i=1; i<N; i++)
phi[i]=i;
for(int i=2; i<N; i++)
{
if(!A[i])
{
phi[i]=i-1;
for(int j=i*2; j<N; j+=i)
{
A[j]=1;
phi[j]=phi[j]/i*(i-1);
}
}
}
}
LL que[N];
LL solve(int n,int m)///容斥定理的实现
{
int i,j,cnt=0;
for(i=2; i*i<=n; i++)
{
if(n%i==0)
{
primes[cnt++]=i;
while(n%i==0)
n/=i;
}
}
if(n>1)
primes[cnt++]=n;
LL front=0;
LL sum=0,uu;
que[front++]=-1;;
for(i=0; i<cnt; i++)
{
uu=front;
for(j=0; j<uu; j++)
que[front++]=que[j]*primes[i]*(-1);
}
for(int i=1; i<front; i++)
sum+=m/que[i];
return sum;///不互质的个数
}
int main()
{
int t,num=1;
//freopen("E:\\in.txt","r",stdin);
scanf("%d",&t);
Phi();
while(t--)
{
scanf("%d%d%d%d%d",&a,&b,&c,&d,&k);
if(k==0)
{
printf("Case %d: 0\n",num++);
continue;
}
LL p=b/k,q=d/k;
if(p>q)///p取较小值
{
LL tmp=p;
p=q;
q=tmp;
}
LL sum=0,sum2=(LL)(p*(q-p));
for(int i=1; i<=p; i++)
sum+=phi[i];
//printf("%lld\n",sum);
for(int i=p+1; i<=q; i++)
{
sum2-=solve(i,p);
//printf(" %lld\n",sum2);
}
printf("Case %d: %lld\n",num++,sum+sum2);
}
return 0;
}