Co-prime
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3216 Accepted Submission(s): 1245
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 <= 1015) and (1 <=N <= 109).
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}.
题意:给定一个区间[a,b],求该区间内与n互素的数,(互素:一个数x与n没有相同的因子,除1外)。
思路:由于区间范围太大,遍历每个数肯定不行。求区间[a,b]内的所有与n互素的数,即可以转化为求区间[1,b]的所有与n互素的数减去[1,a-1]的所有与n互素的数。先求出n的所有质因子,存入数组subprime[i]。b/subprime[i] 即为[1,b]中能被subprime[i]整除的数的数量。这里就用到包含排斥原理。
两个集合时: |A∪B| =|A∪B| = |A|+|B| - |A∩B |
三个集合时:|A∪B∪C| = |A|+|B|+|C| - |A∩B| - |B∩C| - |C∩A| + |A∩B∩C|
多个时,以此类推,加减循环。
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<bitset>
#define MAXN 100005
using namespace std;
bitset<MAXN>isprime;
long long prime[MAXN];
long long subprime[MAXN];
long long a[MAXN];
long long cnt,cnt2;
void is_prime(){//筛选法求素数,时间复杂度为O(n)
isprime.set();//把isprime中的所有数都置为1
long long i,j;
cnt=0;
isprime[1]=0;
for(i=2;i<=MAXN;i++){
if(isprime[i]){
prime[cnt++]=i;
for(j=i+i;j<=MAXN;j+=i){
isprime[j]=0;
}
}
}
}
void f(long long n){//分解n的质因数
long long i,j;
cnt2=0;
for(i=0;prime[i]<=sqrt(n*1.0);i++){
if(n%prime[i]==0){
subprime[cnt2++]=prime[i];
while(n%prime[i]==0){//反复除去相同质因子,到最后一定会只剩下1或者一个大于sqrt(n)的素数
n/=prime[i];
}
}
}
if(n>=2){//如果留下了一个大于2的数,那这个数一定是素数,而且是它的因子
subprime[cnt2++]=n;
}
}
long long solve(long long x){//包含排斥原理
long long i,j,cur,k,sum=0;
a[0]=-1;
k=1;
for(i=0;i<cnt2;i++){
cur=k;
for(j=0;j<cur;j++){
a[k++]=subprime[i]*a[j]*(-1);//包含排斥原理是加减循环的,所以每次都要乘-1
}
}
for(i=1;i<k;i++){
sum+=x/a[i];
}
return sum;
}
int main(){
long long i,j,t,ans,n,m,a,b,cnt,cases;
cin>>t;
is_prime();
cases=1;
while(t--){
cin>>a>>b>>n;
f(n);
ans=(b-solve(b))-(a-1-solve(a-1));
printf("Case #%d: ",cases++);
cout<<ans<<endl;
}
return 0;
}