Co-prime
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4433 Accepted Submission(s): 1755
Problem Description
Given a number N, you are asked to count the number of integers between A and B inclusive which are relatively prime to N.
Two integers are said to be co-prime or relatively prime if they have no common positive divisors other than 1 or, equivalently, if their greatest common divisor is 1. The number 1 is relatively prime to every integer.
Two integers are said to be co-prime or relatively prime if they have no common positive divisors other than 1 or, equivalently, if their greatest common divisor is 1. The number 1 is relatively prime to every integer.
Input
The first line on input contains T (0 < T <= 100) the number of test cases, each of the next T lines contains three integers A, B, N where (1 <= A <= B <= 10
15) and (1 <=N <= 10
9).
Output
For each test case, print the number of integers between A and B inclusive which are relatively prime to N. Follow the output format below.
Sample Input
2 1 10 2 3 15 5
Sample Output
Case #1: 5 Case #2: 10HintIn the first test case, the five integers in range [1,10] which are relatively prime to 2 are {1,3,5,7,9}.
Source
Recommend
题意:[A,B]区间内,与N互质的数的个数。可以把问题转换为[1,B]区间的个数减去[1,A-1]区间的个数。现在的问题就是如何求[1,m]中与n互质的数的个数。可求出[1,m]区间与n不互质的数的个数,假设为num,那么我们的答案就是:m-num。然后问题就是如何求[1,m]区间与n不互质的数的个数。
可以举例说明
m=12,n=30.
第一步:求出n的质因子:2,3,5;
第二步:(1,m)中是n的因子的倍数当然就不互质了(2,4,6,8,10,12)->n/2 6个 (3,6,9,12)->n/3 4个, (5,10)->n/5 2个。
答案显然不是全加起来。里面明显出现了重复的,我们现在要处理的就是如何去掉那些重复的了!
第三步:这里就需要用到容斥原理了,公式就是:n/2+n/3+n/5-n/(2*3)-n/(2*5)-n/(3*5)+n/(2*3*5)。发现除数是奇数个的时候是加,偶数个的时候是减。
#include<iostream>
using namespace std;
long long a[1000],num;
long long mod=1e9+7;
void init(long long n)//分解质因数
{
long long i;
num=0;
for(i=2;i*i<=n;i++)
{
if(n%i==0)
{
a[num++]=i;
while(n%i==0)
n=n/i;
}
}
if(n>1)
a[num++]=n;
}
long long rongchi(long long m)
{
long long que[10000],i,j,k,sum=0;
int t=0;
que[t++]=-1;
for(i=0;i<num;i++)
{
k=t;
for(j=0;j<k;j++)
que[t++]=que[j]*a[i]*(-1);
}
for(i=1;i<t;i++)
sum=sum+m/que[i];
return sum;
}
int main()
{
int t;
int cas=0;
long long a,b,n;
scanf("%d",&t);
while(t--)
{
//cout<<le<<" "<<ri<<endl;
long long aans=0;
//scanf("%d%d%d",&a,&b,&n);
cin>>a>>b>>n;
init(n);
// cout<<a<<endl;
aans=b-rongchi(b)-(a-1-rongchi(a-1));
//cout<<1<<endl;
printf("Case #%d: ",++cas);
printf("%lld\n",aans);
}
}