POJ 2773 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 


代码与解释

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int pri[1000000];
int gcd(int a, int b)
{
    return b?gcd(b,a%b):a;
}
int main()
{
    int m,k;
    while (~scanf("%d%d",&m,&k))
    {
        int i,t;
        t = 0;
        for (i = 1; i <= m; i++)
        {
            if (gcd(m, i) == 1)
                pri[t++] = i;
/*
先找出比m小的且与m互素的数,且记录总个数t;
当k可以整除t时,也就是第n*t个数,此时为(k/t-1)个m加上比m小的最大素数。
当k不可以整除t时,k/t*个m加上第k%t-1个与m互素且比m小的数就是所求
例如m=9
比m小且与之互素的数为1,2,4,5,7共5个数。
若求第10个与m互素的数就是m+7=16
1,2,4,5,7,10,11,13,14,16是前十个与m互素的数。
若求第7个则是m+prime[1]=11;
*/
        }
        if (k % t)
            printf("%d\n",k/t*m+pri[k%t-1]);
        else
            printf("%d\n",(k/t-1)*m+pri[t-1]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lanshan1111/article/details/81564858