Happy 2006 (poj_2773) 欧几里德
2016-05-20 19:48
295 查看
Happy 2006
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
Sample Output
题目大意:给出两个数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);
}
}
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 10879 | Accepted: 3788 |
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);
}
}
相关文章推荐
- 快速幂。素数筛选。辗转相除。
- 欧几里德和扩展欧几里德算法
- poj 1061(数论之欧几里德及其扩展)
- 最大公倍数和最小公倍数
- Java实现求最大公约数和最小公倍数
- 欧几里德算法扩展
- poj2115欧几里德扩展
- 最大公约数算法详解
- 【暑期第二次训练赛】小火山的跳子游戏
- 扩展欧几里德
- 欧几里德 java
- 欧几里德 和 拓展欧几里德算法
- Wolf and Rabbit (hdu_1222) 欧几里德
- 欧几里德算法及拓展
- 扩展欧几里德一系列算法
- 欧几里德算法&&扩展欧几里德算法 (小推+模板)
- 辗转相除法(欧几里得算法)java实现
- Android之ListView使用方法-ArrayAdapter-SimpleAdapter-BaseAdapter
- Android 5.x Theme 与 ToolBar 实战
- Android学习_广播