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.
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的质因子,利用二分法,利用容斥原理求出不互质的数目个数并减去。直到i=k。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define LL long long
#define maxn 70
LL p[maxn];
LL make_ans(LL num,int m)//1到num中的所有数与m个质因子不互质的个数 注意是不互质哦
{
LL ans=0,tmp,i,j,flag;
for(i=1;i<(LL)(1<<m);i++)
{ //用二进制来1,0来表示第几个素因子是否被用到,如m=3,三个因子是2,3,5,则i=3时二进制是011,表示第2、3个因子被用到
tmp=1,flag=0;
for(j=0;j<m;j++)
if(i&((LL)(1<<j)))//判断第几个因子目前被用到
flag++,tmp*=p[j];
if(flag&1)//容斥原理,奇加偶减
ans+=num/tmp;
else
ans-=num/tmp;
}
return ans;
}
int main()
{
LL a,b,i;
LL m,n;
while(~scanf("%lld%lld",&m,&n))
{
memset(p,0,sizeof(p));
LL num=0;
LL mm=m;
for(LL i=2;i*i<=mm;i++)
{
if(mm%i==0)
p[num++]=i;
while(mm%i==0)
mm/=i;
}
if(mm!=1)
p[num++]=mm;
LL l=1;
LL r=((LL)1<<31);
LL ans=0;
LL res=0;
while(l<=r)
{
LL mid=(l+r)>>1;
ans=mid-make_ans(mid,num);
if(ans>n)
r=mid-1;
else if(ans<n)
l=mid+1;
else{
res=mid;
r=mid-1;
}
}
cout<<res<<endl;
}
return 0;
}
并且在网上看到另一种解法:
http://blog.csdn.net/huangshuai147/article/details/51277645
如果知道欧几里德算法的话就应该知道gcd(b×t+a,b)=gcd(a,b) (t为任意整数)
则如果a与b互素,则b×t+a与b也一定互素,如果a与b不互素,则b×t+a与b也一定不互素
故与m互素的数对m取模具有周期性,则根据这个方法我们就可以很快的求出第k个与m互素的数
假设小于m的数且与m互素的数有k个,其中第i个是ai,则第m×k+i与m互素的数是k×m+ai
附代码
#include<stdio.h>
int s[1000005];
int gcd(int a,int b)
{
if(b==0)
{
return a;
}
else
{
return gcd(b,a%b);
}
}
int main()
{
int m,k;
while(scanf("%d%d",&m,&k)!=EOF)
{
int i;
int num=0;
for(i=1;i<=m;i++)
{
if(gcd(m,i)==1)
{
s[num++]=i;
}
}
if(k%num==0)
{
printf("%d\n",(k/num-1)*m + s[num-1]);
}
else
{
printf("%d\n",k/num*m + s[k%num-1]);
}
}
return 0;
}