WEYuLi的专栏

大学最美好的回忆就是奋斗acm,加油!!

poj 2773 Happy 2006(求第k个与n互质的数)
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;
}


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/WEYuLi/article/details/17111757
个人分类: poj 数论
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

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

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭