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<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<vector>
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;i<l&&pri[i]*pri[i]<=num;i++)
    {
        if(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;i<k;i++)
    {
        if(state&(1<<i))
        {
            countt++;
            v*=factor[i];
        }
    }
    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<<k);s++)
            ans-=get(r,s);
        if(l>1)
        {
            long long ans2=l-1;
            for(int s=1;s<(1<<k);s++)
            ans2-=get(l-1,s);
            ans-=ans2;
        }
        printf("Case #%d: %lld\n",t++,ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值