关闭

poj 2773 Happy 2006(求第k个与n互质的数)

标签: 求第k个与n互质的数
595人阅读 评论(0) 收藏 举报
分类:
Happy 2006
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 8779   Accepted: 2913

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

1
3
5


题意:给出m、k,求k个与m互质的数。
思路:我们知道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互素的数。

AC代码:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <queue>
#include <ctime>

#define ll __int64

using namespace std;

const int maxn = 1000000;
int prime[maxn + 5];
bool vis[maxn + 5], flag[maxn + 5];
int cnt;
void getprime()
{
    memset(vis, false, sizeof(vis));
    cnt = 0;
    for(int i = 2; i <= maxn; i++)
        if(!vis[i])
        {
            prime[cnt++] = i;
            for(int j = 1; j * i<= maxn; j++)
                vis[j * i] = true;
        }
}

int euler(int n)
{
    memset(flag, false, sizeof(flag));
    int ret = n, m = n;
    for(int i = 0; prime[i] * prime[i] <= n; i++)
    if(n % prime[i] == 0)
    {
        ret = ret / prime[i] * (prime[i] - 1);
        while(n % prime[i] == 0) n /= prime[i];
        for(int j = prime[i]; j <= m; j += prime[i])
        flag[j] = true;
    }
    if(n > 1)
    {
        ret = ret / n * (n - 1);
        for(int j = n; j <= m; j += n)
        flag[j] = true;
    }
    return ret;
}
int find(int n, int id)
{
    int cnt = 0;
    for(int i = 1; i <= n; i++)
    {
        if(!flag[i]) cnt++;
        if(cnt == id) return i;
    }
    return -1;
}
int main()
{
    int m, k;
    getprime();
    while(cin>>m>>k)
    {
       if(m == 1)
       {
           cout<<k<<endl;
           continue;
       }
       int len = euler(m);
       cout<<((k - 1)/ len) * m + find(m, (k - 1) % len + 1)<<endl;
    }
    return 0;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:246812次
    • 积分:6260
    • 等级:
    • 排名:第4071名
    • 原创:397篇
    • 转载:11篇
    • 译文:0篇
    • 评论:11条
    最新评论