您的位置:首页 > 移动开发

Happy 2006 POJ - 2773 数论

2017-09-28 23:13 393 查看
题目链接

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 大的数,

思路:

第一种: 暴力, 若a和b互素的话,则b*t+a和b一定互素,反之亦然,与m互素的数对m取余的话有一定的周期性规律,然后就可以直接算,假设小于m的数且与m互素的数有k个,其中第i个是ai,则第m×k+i与m互素的数是k×m+ai.

第二种:

利用欧拉函数找出与m互质的数的数目,并且筛选出与m互质的数,然后剩下的就是和暴力差不多的过程了.

代码:

第一种:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;

typedef long long LL;
const int maxn = 1e6 +10;
int a[maxn];

int gcd(int a, int b){
return b ? gcd(b, a% b) : a;
}

int main(){
int k, m;
ios::sync_with_stdio(false);
while(cin >> m >> k){
int cnt = 0;
k--;
for(int  i = 1; i <= m; ++i)
if(gcd(i, m) == 1)
a[cnt++] = i;
cout<<a[k % cnt] + k / cnt * m<<endl;
}return 0;
}


第二种:

#include<cstring>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;

typedef long long LL;
const int maxn = 1e6 +10;
bool prime[maxn];

int euler(int n){
int ans = n;
int m = n;
memset(prime, false, sizeof(prime));
for(int i = 2; i * i <= n; ++i)
if(n % i == 0){
ans -= ans / i;
for(int j = 1; j * i <= m; ++j)
prime[j * i] = true;
while(n % i == 0)
n /= i;
}if(n > 1){
ans -= ans / n;
for(int j = 1; j * n <= m; ++j)
prime[j * n] = true;
}return ans;
}

int main(){
int n, k;
ios::sync_with_stdio(false);
while(cin >> n >> k){
int t = euler(n);
int tt = k / t;
if(k % t == 0) tt--;
int num = 0,cur;
t = k - t * tt;
for(int i = 1; i <= n; ++i){
if(!prime[i])
++num;
if(num == t){
cur = i;
break;
}
}cout<<cur + n * tt<<endl;
}return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: