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.

链接🔗

[POJ 2773]Happy 2006

题解

因为
gcd(x,y)=gcd(y,x%y)gcd(x,y) = gcd(y,x\%y)
gcd(x,y)=gcd(yt+x,y)gcd(x,y) = gcd(y*t+x,y)
如果 gcd(a,b)=1gcd(a,b) = 1 ,那么 gcd(a+bt,b)=1gcd(a+b*t,b) = 1

因此,与 mm 互质的数对 mm 取模具有周期性,因此我们可以找到 [1,m][1,m] 的互质数,然后根据周期性推出其他的数

代码

#include <cstdio>
#include <algorithm>
using namespace std;
const int maxd = 1e6+10;
int arr[maxd],a,b;
int gcd(int x,int y){return (!y)?x:gcd(y,x%y);}
int main()
{
    // freopen("a.in","r",stdin);
    // freopen("k.out","w",stdout);
    while(scanf("%d %d",&a,&b)!=EOF)
    {
        int len = 0;
        for(int i=1;i<=a;i++)
            if(gcd(i,a) == 1)
                arr[len++] = i;
        if(b%len==0) printf("%d\n",(b/len-1)*a+arr[len-1]);
        else printf("%d\n",b/len*a+arr[b%len-1]);
    }
    return 0;
}