Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 10879 | Accepted: 3788 |
Description
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
Output
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);
}
}