[HDU4135]CO Prime(容斥)

也许更好的阅读体验
\(\mathcal{Description}\)
\(t\)组询问,每次询问\(l,r,k\),问\([l,r]\)内有多少数与\(k\)互质
\(0<l<=r<=10^{15},k<=10^{9},t<=100\)
\(\mathcal{Solution}\)
考虑 容斥
先求\([l,r]\)内出有多少数与\(k\)不互质,再用总数减去即可
\(k\)质因子分解为\(p_1^{k_1}·p_2^{k_2}·...p_n^{k_n}\)
\([l,r]\)内与\(p\)不互质的数有\(r/p-(l-1)/p\)
接下来的操作就是基本操作了:
全部的数减去与\(k\)\(1\)个因子不互质的数加上与\(k\)的2个因子不互质的数减去....如此反复
Code

/*******************************
Author:Morning_Glory
LANG:C++
Created Time:2019年07月07日 星期日 14时26分28秒
*******************************/
#include <cstdio>
#include <fstream>
#define ll long long
using namespace std;
const int maxn = 300005;
//{{{cin
struct IO{
    template<typename T>
    IO & operator>>(T&res){
        res=0;
        bool flag=false;
        char ch;
        while((ch=getchar())>'9'||ch<'0')    flag|=ch=='-';
        while(ch>='0'&&ch<='9') res=(res<<1)+(res<<3)+(ch^'0'),ch=getchar();
        if (flag)    res=~res+1;
        return *this;
    }
}cin;
//}}}
int t,cnt;
ll l,r,k,ans;
ll prime[maxn];
//{{{get_prime
void get_prime (ll k)
{
    cnt=0;
    for (ll i=2;i*i<=k;++i)
        if (k%i==0){
            prime[++cnt]=i;
            while (k%i==0)  k/=i;
        }
    if (k>1)    prime[++cnt]=k;
}
//}}}
//{{{dfs
void dfs (int x,bool flag,ll sum)//x当前是哪个因子  flag 选则的因子个数是否为奇数 sum 选择的因子的乘积 
{
    if (x==cnt+1){
        if (flag)   ans+=r/sum-(l-1)/sum;
        else    ans-=r/sum-(l-1)/sum;
        return;
    }
    dfs(x+1,flag^1,sum*prime[x]);
    dfs(x+1,flag,sum);
}
//}}}
int main ()
{
    cin>>t;
    for (int i=1;i<=t;++i){
        cin>>l>>r>>k;
        ans=0;
        get_prime(k);
        dfs(1,1,1);//默认选择了 1 
        printf("Case #%d: %lld\n",i,ans);
    }
    return 0;
}

转载于:https://www.cnblogs.com/Morning-Glory/p/11146415.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值