POJ2773 Happy 2006

Description

Two positive integers are said to be relatively prime to each other if the Great Common Divisor (GCD) is 1. For instance, 1, 3, 5, 7, 9...are all relatively prime to 2006. 

Now your job is easy: for the given integer m, find the K-th element which is relatively prime to m when these elements are sorted in ascending order. 

Input

The input contains multiple test cases. For each test case, it contains two integers m (1 <= m <= 1000000), K (1 <= K <= 100000000).

Output

Output the K-th element in a single line.

Sample Input

2006 1
2006 2
2006 3

Sample Output

1
3
5

题目大意:给出 m , k ,求与 m 互质的第 k 个数。

题解:二分答案+容斥原理+质因数分解

首先可以根据线性的性质来二分答案,并且
判断 1-ans 之间有多少个数和 m 互素,互素的数的个数可以表示成为 [ ans - ( 和 m 不互素的数
的个数 ) ],所以可以找出在 ans 内有多少数和 m 不互素,这时候容斥定理就有了用武之地,
根据 m 的范围可知,就算按照最小的质数 2 计算,其质因子数不会超过 20 个,所以可以
在这 20 个质因子中利用容斥定理求出,这道题因为集合较多,所以要用深搜进行容斥定

理的运算

附代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#define MAXN 1000010
using namespace std;
int s,c=0;
long long m,k,a[30],prime[MAXN];
bool np[MAXN];
inline int read(){
	int date=0,w=1;char c=0;
	while(c<'0'||c>'9'){if(c=='-')w=-1;c=getchar();}
	while(c>='0'&&c<='9'){date=date*10+c-'0';c=getchar();}
	return date*w;
}
void make(){
	int x=MAXN-10;
	memset(np,false,sizeof(np));
	for(int i=2;i<=x;i++){
		if(!np[i])prime[++c]=i;
		for(int j=1;j<=c&&prime[j]*i<=x;j++){
			np[prime[j]*i]=true;
			if(i%prime[j]==0)break;
		}
	}
}
void dfs(int step,long long now,long long x,bool flag,long long &ans){
	if(step>s)return;
	long long v=now*a[step];
	dfs(step+1,now,x,flag,ans);
	if(flag)ans+=(x/v);
	else ans-=(x/v);
	dfs(step+1,v,x,!flag,ans);
}
long long num(long long x){
	long long ans=0;
	dfs(1,1,x,true,ans);
	return x-ans;
}
int main(){
	make();
	while(~scanf("%d%d",&m,&k)){
		if(m==1){
			printf("%d\n",k);
			continue;
		}
		long long ans;
		s=0;
		for(int i=1;i<=c&&m!=1;i++)
		if(m%prime[i]==0){
			a[++s]=prime[i];
			while(m%prime[i]==0)m/=prime[i];
		}
		long long l=1,r=2147483647,mid;
		while(l<=r){
			mid=l+r>>1;
			long long t=num(mid);
			if(t==k)ans=mid;
			if(t>=k)r=mid-1;
			else l=mid+1;
		}
		printf("%lld\n",ans);
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值