###### 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;
}


#### POJ_2773_Happy 2006_ 欧几里得算法

2016-04-28 21:28:16

#### POJ 2773-Happy 2006(欧拉函数)

2015-04-08 19:28:39

#### nyoj 762第k个互质数 poj 2773Happy 2006

2016-05-26 10:30:55

#### poj2773求第K个与m互质的数

2014-02-18 21:44:53

#### POJ 2773 Happy 2006 (公式法 or 二分容斥定理)

2014-03-04 09:54:31

#### poj 2773Happy 2006

2016-03-26 11:19:40

#### POJ 2773：Happy 2006

2015-12-05 18:24:12

#### 容斥原理 —— 求1~n有多少个数与k互质（二进制算法详细解释&模板）

2016-07-22 20:38:14

#### nyoj 第k个互质数（二分+容斥原理）

2017-03-20 10:02:29

#### 容斥原理求1到n与k互质个数

2016-10-10 23:21:23

## 不良信息举报

poj 2773 Happy 2006（求第k个与n互质的数）