您的位置:首页 > 移动开发

POJ 2773 Happy 2006

2013-05-03 20:03 225 查看
[align=center]Happy 2006[/align]

Time Limit: 3000MSMemory Limit: 65536K
Total Submissions: 7874Accepted: 2551
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

Source

POJ Monthly--2006.03.26,static
考察点:二分查找和 容斥原理
刚看到这题的时确实是有点晕,虽然知道是用容斥原理,可还是不会用,有一个地方没有想到。其实这个题在概率上就学过,给定一个范围 求不能被n或m整除的数字,可以先求能够整除的并集,然后再从整体中将这部分减去,剩下的就是所求。 求不能被n或m整除的数字就是运用容斥原理啊。
将这题转化一下,二分答案,看那个区间中有多少个不能被整除的数。而不能被整除,可以转化为不能被一系列数整除,因为数字是可以转化为相乘的形式的,然后在运用容斥原理就好了。
二分的时候注意找到答案并不是最终的答案,有可能那个满足题意的答案值取大了。后面那个数可能与n最大公约数不为1

#include <stdio.h>
#include <string.h>
#include <math.h>
int INF=0x7fffffff;
int a[1000000],b[1000000],top,level;
long long int dfs_res;
int main()
{
long long int binary_search(int l,int r,int m);
long long int i,j,n,m,s,t;
while(scanf("%lld %lld",&n,&m)!=EOF)
{
if(n==1)
{
printf("%lld\n",m);
continue;
}
top=0;
for(i=2;n!=1; )
{
if(n%i==0)
{
a[top++]=i;
while(n%i==0)
{
n=n/i;
}
}
if(i==2)
{
i+=1;
}else
{
i+=2;
}
}
s=binary_search(1,INF,m);
printf("%lld\n",s);
}
return 0;
}
void dfs(int le,int pt,long long int val)
{
int i,j;
long long int s;
for(i=pt;i<=top-1;i++)
{
b[le]=a[i];
if(le==level)
{
for(j=1,s=1; j<=level; j++)
{
s=s*b[j];
}
dfs_res+=(val/s);
}else
{
dfs(le+1,i+1, val);
}
}
}
long long int binary_search(int l,int r,int m)
{
long long int i,j,n,s1,key,res,k=0,mid;
while(l<=r)
{
mid=(l+r)/2;
for(i=0,s1=0;i<=top-1;i++)
{
s1+=(mid/a[i]);
}
for(i=2,key=-1; i<=top; i++)
{
dfs_res=0;
level=i;
dfs(1,0,mid);
s1+= key* dfs_res;
key=key*-1;
}
s1= mid-s1;
if(s1>m)
{
r=mid-1;
}else if(s1<m)
{
l=mid+1;
}else
{
if(k==0)
{
res=mid;
}else if(res>mid)
{
res=mid;
}
r=mid - 1;
}
}
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: