Happy 2006 (poj_2773) 歐幾里德


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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章