HDU 4135 Co-prime

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

题目

求在区间 [ l , r ] 之间有多少个数与 n 互质

题解
  1. 相对于互质,不互质的数更好求
  2. 只要求出n的质因数,再看看 [ l , r ] 有多少个数含有这些因子
  3. 这时就需要一些容斥原理,奇加偶减
#include<bits/stdc++.h>
using namespace std;
int vis[1000010],cnt,tot;
long long p[1000010],a[1000010];
void sol(long long x)
{
	tot=0;
	for(int i=1; p[i]*p[i]<=x&&i<=cnt; i++)
	{
		if(x%p[i]==0)
		{
			a[++tot]=p[i];
			while(x%p[i]==0) x=x/p[i];
		}
	}
	if(x>1) a[++tot]=x;
}
long long print(long long x)
{
	long long ans=0,i,s,t,j;
	for(i=1; i<(1ll<<tot); i++)
	{
		s=0;
		t=1;
		for(j=1; j<=tot; j++)
		{
			if(i&(1ll<<(j-1)))
			{
				s++;
				t=t*a[j];
			}
		}
		if(s&1) ans+=x/t;
		else ans-=x/t;
	} 
	return ans;
}
int main()
{
	freopen("a.txt","r",stdin);
	long long t,tt,i,l,r,n,j;
	scanf("%lld",&tt);
	cnt=0;
	tot=0;
	memset(vis,0,sizeof(vis));
	for(i=2; i<1000010; i++)
	{
		if(vis[i]==0)
		{
			p[++cnt]=i;
			for(j=i*i; j<1000010; j+=i) vis[j]=1;
		}
	}
	for(t=1; t<=tt; t++)
	{
		scanf("%lld%lld%lld",&l,&r,&n);
		sol(n);
		printf("Case #%lld: %lld\n",t,r-print(r)-l+1+print(l-1));
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值