题目描述:
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.大意:
如果大公约数(GCD)为1,则两个正整数被称为相对素数。例如,1、3、5、7、9……都是2006年的相对素数。
现在你的工作很简单:对于给定的整数m,找到第K个元素,当这些元素按升序排序时,它对m是相对素数
输入格式:
The input contains multiple test cases. For each test case, it contains two integers m (1 <= m <= 1000000), K (1 <= K <= 100000000).
输入包含多个测试用例。对于每个测试用例,它包含两个整数m(1<=m<=1000000)、K(1<=K<=100000000)。
输出格式:
Output the K-th element in a single line.
在单行中输出第K个元素。
输入输出样例
输入 #1
2006 1
2006 2
2006 3
输出 #1
1
3
5
思路:
先打表把m的相对素数(小于m)都找到,根据数据范围,可以直接for循环,不用筛,再找到在第几个m的第几个相对素数。
代码:
#include <iostream>
#include <cstdio>
using namespace std;
#pragma GCC optimize(2)
int a,b;
const int n=1e6;
int p[n+5]={};
int gcd(int a,int b){
if(b==0){
return a;
}
return gcd(b,a%b);
}
int main(){
while(cin>>a>>b){
int sum=0;
for(int i=1;i<=a;++i){
if(gcd(i,a)==1){
p[++sum]=i;
}
}
int c,d;
c=b%sum;
d=b/sum;
if(c==0){
d--;
c=sum;
}
printf("%d\n",p[c]+d*a);
}
return 0;
}