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 Source
POJ Monthly--2006.03.26,static
|
[Submit] [Go Back] [Status] [Discuss]
思路:
就是在0到0x3f3f3f3f3f3f3f3f(无穷大的数)之间找一个数,它是与n互质的数的第k大数!(但是不知道二分查找的时候为什么找到了还要循环!)
代码:
#include <stdio.h>
#include <string.h>
#include <algorithm>
#define LL long long
using namespace std;
LL p[10]={0},k;
void getp(int n)
{
k=0;
for(int i=2;i*i<=n;i++)
{
if(n%i==0)
p[k++]=i;
while(n%i==0)
n/=i;
}
if(n>1) p[k++]=n;
}
LL nop(LL m)
{
LL que[10005],top=0;
que[top++]=-1;
for(LL i=0;i<k;i++)
{
LL t=top;
for(LL j=0;j<t;j++)
{
que[top++]=que[j]*p[i]*(-1);
}
}
LL sum=0;
for(int i=1;i<top;i++)
{
sum+=m/que[i];
}
return sum;
}
int main()
{
int m,kk;
while(scanf("%d%d",&m,&kk)!=EOF)
{
getp(m);
LL l=0,mid,r=0x3f3f3f3f3f3f3f3f;
LL ans;
while(l<=r)
{
mid=(l+r)>>1;
LL t=mid-nop(mid);//这个t一定是LL型的,不能是int型的!
if(t<kk)
{
l=mid+1;
}
else if(t==kk)
{
r=mid-1;//之前没写这个就不对,不知道为什么?
ans=mid;//为什么找到之后还要进行循环?
// break; //而不能break;
}
else
{
r=mid-1;
}
}
printf("%lld\n",ans);
}
return 0;
}