HDU 4135 Co-prime(容斥原理)

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}.

一道容斥的题,之前做过一道比这个难一些的,而其这个不需要去筛选一个范围内的数的素英制,所以求素因子的方法也不太一样,并且这个数的可以大到10e9次,就求素因子要注意一下

#include
#include
#include
#include
#include
#include
using namespace std;
int factor[20];
int k;

bool prime[31623];
int pri[3500];
int l=0;
void getPrime()//先筛素数
{
    memset(prime,true,sizeof(prime));
    for(int i=2;i<=31622;i++)
        if(prime[i])
        {
            pri[l++]=i;
            for(int j=i+i;j<=31622;j+=i)
                prime[j]=false;
        }
}
void getFactor(int num)//求一个的数素因子
{
    k=0;
    int m=num;
    for(int i=0;iif(m%pri[i]==0)
        {
            factor[k++]=pri[i];
            while(m%pri[i]==0)
                m/=pri[i];
        }
        if(m==1)break;
    }
    if(m>1)
        factor[k++]=m;
}
long long get(long long limit,int state)//在一个状态组合下的在limit的范围内的个数
{
    int countt=0;
    int v=1;
    for(int i=0;iif(state&(1<long long ans=limit/v;
    if(countt%2)
        return ans;
    else
        return -ans;
}
int main()
{
    getPrime();
    int n;
    long long l,r;
    int num;
    int t=1;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%lld%lld%d",&l,&r,&num);

        long long ans=r;
        getFactor(num);
        for(int s=1;s<(1<if(l>1)
        {
            long long ans2=l-1;
            for(int s=1;s<(1<1,s);
            ans-=ans2;
        }
        printf("Case #%d: %lld\n",t++,ans);
    }
    return 0;
}

你可能感兴趣的:(组合数学,容斥原理)