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
这道题出的真的是很有水平,题意很简单,给出两个数n,k,求与n这个数互素的第k个数,输出即可。
这道题有两种做法
第一种:因为gcd(a,m)==gcd(m*t+a,m),这个很好理解,自己推算下就知道了,所以我们可以求出1-m中与m互素的各个数存在数组中,然后后面的数通过上面哪个公式就可以求出。因为这道题时间3000ms,所以即使m的范围较大,但是还是能过。
第二种:用容斥定理和二分做,中间有个坑点,在代码中给解释说明。
第一种做法代码这种做法险过
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
int gcd(int n,int m)
{
if(m==0)
return n;
return gcd(m,n%m);
}
int a[1000010];
int main()
{
int m,k;
while(~scanf("%d%d",&m,&k))
{
memset(a,0,sizeof(a));
int tot=0;
for(int i=1;i<=m;i++)
{
if(gcd(i,m)==1)
a[++tot]=i;
}
a[0]=a[tot];
printf("%d\n",(k-1)/tot*m+a[k%tot]);
}
return 0;
}
第二种代码由于二分的作用,时间上节省了好多
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
int a[1000010];
int tot;
void prime(int n)
{
tot=0;
for(int i=2; i*i<=n; i++)
{
if(n%i==0)
{
a[tot++]=i;
while(n%i==0)
n/=i;
}
}
if(n>1)
a[tot++]=n;
}
ll sud(ll n)
{
ll ans=0;
for(int i=1; i<(1<<tot); i++)
{
ll flag=0,sum=1;
for(int j=0; j<tot; j++)
{
if(i&(1<<j))
{
sum*=a[j];
flag++;
}
}
if(flag%2==1)
ans+=n/sum;
else
ans-=n/sum;
}
return n-ans;
}
int main()
{
int n;
ll k;
while(~scanf("%d%lld",&n,&k))
{
prime(n);
ll ans=0;
ll h=1,mid=0,w=1e15;
while(h<=w)
{
mid=(h+w)/2;
ll t=sud(mid);
if(t>=k)//t==k和t>k写一块是因为在t相同的情况下,尽量找到更小的mid,
{
w=mid-1;
if(t==k)//这里不能break掉,因为有可能不同的mid有相同的
//与n互素的数例如2006 1856这个样例,不这样写的
//话输出的就不是4011,可以自己试试。
ans=mid;
}
else
h=mid+1;
}
printf("%lld\n",ans);
}
return 0;
}