hdu4135(容斥入门题)

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=4135

题目意思:给定两个数 a b和一个数 n  求[a,b]范围内与n互素的数的个数

思路:我们可以用容斥计算出[1,B]之间和[1,A-1]之间的与N互质的数,然后相减即可。然后我们用一种快速的方法求出[1,X]之间的与N互质的数,首先我们求出N的质因子,[1,X]之间与N的质因子成倍数关系的数肯定与N不成互质关系。


code:

#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
#define maxn 100000
ll p[maxn];
int len;
ll a,b,n;
void init(ll n)//分解质因数
{
    len=0;
    for(int i=2;i*i<=n;i++)
    {
        if(n%i==0)
        {
            p[len++]=i;
            while(n%i==0)
                n/=i;
        }
    }
    if(n>1)
    p[len++]=n;
}
ll solve(ll n)
{
    ll y=(ll)(1<<len);//情况的数量为y-1
    ll res=0;
    for(int i=1;i<y;i++)
    {
        ll flag=0;
        ll temp=1;
    for(int j=0;j<len;j++)
        if(i&(ll)(1<<j))
        {
            flag++;
            temp*=p[j];
        }
        if(flag&1)
            res+=n/temp;
        else res-=n/temp;
    }
    return res;
}
int main()
{
    ios::sync_with_stdio(false);
    int T;
    cin>>T;
    int kcas=1;
    while(T--)
    {
        cin>>a>>b>>n;
        init(n);
        ll ans=(b-solve(b))-(a-1-solve(a-1));
        cout<<"Case #"<<kcas++<<": "<<ans<<endl;
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值