题目:
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: 10
Hint
In the first test case, the five integers in range [1,10] which are relatively prime to 2 are {1,3,5,7,9}.
题意:输入三个整数a,b,n,求区间[a,b]内与n是相对素数(若两个整数的最大公因数是1,则称它们为相对素数)的整数个数。
大概思路:求[a,b]区间内的相对素数,可以用[1,b]区间内的相对素数数减去区间[1,a)内的相对素数数。求区间[1,m]的区间的相对素数,可以从反面想,可以求出在区间内与n不是相对素数的整数数。先求出n的所有质因数,是n质因数整数倍的数一定不是n的相对素数,但是这里会有交集,利用容斥定理求出与n不是相对素数的个数。
代码:
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
long long a[1000],num;
///求n的质因数
void f(long long n)
{
long long i;
num=0;
for(i=2;i*i<=n;i++){///循环只需要到根号n
if(n%i==0){
a[num++]=i;
while(n%i==0)
n/=i;
}
}
if(n>1)a[num++]=n;
}
///容斥定理(奇加偶减)
long long rongchi(long long m)
{
long long q[10000],i,j,k;
long long sum=0;
int t=0;
q[t++]=-1;
for(i=0;i<num;i++){
k=t;
for(j=0;j<k;j++){
q[t++]=q[j]*a[i]*(-1);
}
}
for(i=1;i<t;i++)
sum+=m/q[i];
return sum;
}
int main()
{
int t;
int cas=0;
long long a,b,n;
scanf("%d",&t);
while(t--){
long long ans=0;
scanf("%lld%lld%lld",&a,&b,&n);
f(n);
ans=b-rongchi(b)-(a-1-rongchi(a-1));
printf("Case #%d: ",++cas);
printf("%lld\n",ans);
}
return 0;
}