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.
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互质的数的个数,我们直接暴力肯定是会超时的,我们不妨换一个思路。先求出1-b的互质的数的个数,再求出1-a互质的数的个数,两者相减即可求得a-b之间互质的数。
我们先对n进行质因数分解,n的质因数肯定要与别的数互质,要不然不会满足与n互质的条件。
有的人会问了你先求出1-a和1-b的数的时间怎么会比我直接求a-b之间数的时间更短呢,实际上我们求1-n与m互质的数有个方法,用n/m可以求得在1-n之间有多少个数能被m整除,(举个例子,n=20,m=4,20/4=5,分别是(4,8,12,16,20)),用总数20-5=15,这15个数就是因数中不存在4的,当然这里4肯定不是质因数,我只是举个例子。
用除法的方法找个数当然比一个一个找要快得多!
假如有两个甚至更多的质因数,我们要注意减去之后一定要加上质因数的交集:A∪B=|A|+|B|-A∩B。
这就是容斥定理。
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <stdio.h>
#include <ctype.h>
#define LL long long
#define ULL unsigned long long
#define mod 1000000007
#define INF 0x7ffffff
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int MAXN = 20005;
const int N = 15;
LL a[55],b[1005];
LL a_,b_,n;
void di_prime()//求出n的质因数
{
LL i,j=0;
for(i=2;i*i<=n;i++){
if(n%i==0){
while(n%i==0) n/=i;
a[++j]=i;
}
}
if(n>1) a[++j]=n;
//printf("%lld",j);
a[0]=j;
//printf("%d%d",a[3],a[2]);
}
LL get_sum(LL mid)//容斥定理的循环,DFS也能写,直接找出深度即可。
{
LL sum=mid,x=0,y;
b[++x]=1;
for(LL i=1;i<=a[0];i++){
y=x;
for(LL j=1;j<=x;j++){
b[++y]=b[j]*a[i]*-1;
sum+=mid/b[y];
}
x=y;
}
return sum;
}
int main()
{
int T,cot=1;
scanf("%d",&T);
while(T--){
scanf("%lld%lld%lld",&a_,&b_,&n);
di_prime();
LL sum1 =get_sum(a_-1);
mem(b,0);
LL sum2 =get_sum(b_);
printf("Case #%d: %lld\n",cot++,sum2-sum1);
mem(a,0),mem(b,0);
}
return 0;
}