[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
",i,ans);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/Morning-Glory/p/11146415.html