首页 > 代码库 > hdu 4135 Co-prime【容斥原理】

hdu 4135 Co-prime【容斥原理】

Co-prime

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1668    Accepted Submission(s): 636


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.
 

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: 10
题目翻译:T组数据,每组给出A,B,N,求区间【A,B】里面有多少个数与N互质!
解题思路:求出所有的数字的与N不互质的情况,然后用总量减去!求不互质的情况,显然就是利用容斥原理,先求出N的质因子,然后去掉【A,B】中含有这些质因子的数,此时应该注意会重复去掉一些数字,记得加上即可,容斥原理的写法有好几种,感觉每种都很牛,比如用数组实现,DFS实现,以及用位运算实现!
数组实现:
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
__int64 a[10],num;
void init(__int64 n){ //求一个数的质因子
    __int64 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;  //这里要记得
}
__int64 haha(__int64 m){ //用队列数组实现容斥原理
    __int64 que[10000],i,j,k,t=0,sum=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(){
    __int64 T,x,y,n,i=1,sum;
    scanf("%I64d",&T);
    while(T--){
           scanf("%I64d%I64d%I64d",&x,&y,&n);
           init(n);
           sum=y-haha(y)-(x-1-haha(x-1));
           printf("Case #%I64d: ",i++);
           printf("%I64d\n",sum);
        }
    return 0;
}
DFS实现:
#include<stdio.h>
#include<math.h>
int p[10],top;
long long ansa,ansb,ans,a,b;
void DFS(int n,bool tag,long long num){
    if(n==top){
        if(tag==1){
            ansa-=a/num;
            ansb-=b/num;
        }
        else{
            ansa+=a/num;
            ansb+=b/num;
        }
        return;
    }
    DFS(n+1,tag,num);
    DFS(n+1,!tag,num*p[n]);
}
int main(){
    int i,j,n,T,k,cnt;
    cnt=1;
    scanf("%d",&T);
    while(T--){
        scanf("%I64d%I64d%d",&a,&b,&n);
        a--;
        ansa=ansb=0;
        top=0;
        for(i=2;i*i<=n;i++){
            if (n%i==0){
                while(n%i==0) n=n/i;
                p[top++]=i;
            }
        }
        if(n>1)
            p[top++]=n;
        DFS(0,0,1);
        printf("Case #%d: %I64d\n",cnt++,ansb-ansa);
    }
    return 0;
}

hdu 4135 Co-prime【容斥原理】