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

Happy 2006 (poj_2773) 欧几里德

2016-05-20 19:48 295 查看
Happy 2006

Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 10879 Accepted: 3788
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,求m的第k个互素数;

解题思路:向用欧几里德求出小于m且与m互素的数,然后由gcd(b*t+a, b)=gcd(b,a)可知与b互素的数有周期性,并且周期为b ;

代码如下:

#include"iostream"
#include"cstdio"
#include"cstring"
using namespace std;
const int maxn = 1000000 + 5;

int prime[maxn]; //用于存1-m内的素数

int gcd(int a, int b){ //求最小公约数
return b == 0 ? a : gcd(b, a%b);
}

int main(){
int m, k;
long long ans;
while(scanf("%d%d", &m, &k) != EOF){
int i, j;
for(i = 1, j = 1;i <= m;i ++)
if(gcd(m, i) == 1) //互素
prime[j ++] = i;
j --;//j表示1-m内的素数个数

/*由gcd(b*t+a, b)=gcd(b,a)
可知与b互素的数有周期性,并且周期为b */
if(k % j != 0)
ans = k/j*m + prime[k%j];
else
ans = (k/j - 1)*m + prime[j];
printf("%lld\n", ans);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  欧几里德