poj 2773 Happy 2006

来源:互联网 发布:软件购买网站 编辑:程序博客网 时间:2024/05/29 04:38

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 12006 22006 3

Sample Output

135
题意:给出m,k,求第k小的与m互质的数。分析:根据gcd的求法,我们可知,求最大公约数的第一步是用大数对小数取余。gcd(a,b)==gcd(a%b,b),进一步推出gcd(a,b)==gcd(a+b, b)。也就是说,当求出了1~m间与m互质的数之后,把这些数加上m就可以得到m~2m间的与m互质的数。而且m~2m间不会有某个与m互质的数被漏掉。因为如果m<=a<=2m,且gcd(a, m)==1,那么gcd(a - m, m)必然等于1。也就是必然有个在1~m间的数a-m,可以通过加m的方式得到a。所以与m互质的数是有周期性的。我们只需要求出第一个周期即可。#include<stdio.h>int p[1000010];int gcd(int a,int b){    return b==0 ? a : gcd(b,a%b);}int main(){    int m,k,i,j;    while(scanf("%d%d",&m,&k)!=EOF)    {        int tot=0;        for(i=1;i<=m;i++)        {            if(gcd(i,m)==1)            {                    p[++tot]=i;            }        }        int ans;        int tmp=k/tot;        int tmp2=k%tot;        if(tmp2==0) ans=(tmp-1)*m+p[tot];        else ans=m*(tmp)+p[tmp2];        printf("%d\n",ans);    }}



                                             
0 0