Happy 2006
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 10084 | Accepted: 3460 |
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.
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
题意:求第k个和m互素的数。
思路:由欧几里得gcd(a,b)=gcd(a+b*t,b),枚举小于m的所有互素的数,然后这些数加上一个m也与m互素,可以由这样的周期性找到第k个的答案。
AC代码如下:
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
int gcd(int a,int b)
{
return b==0 ? a : gcd(b,a%b);
}
int num[1000010],p;
int m;
int main()
{
int i,j;
ll k,ret,ans,pos;
while(~scanf("%d%I64d",&m,&k))
{
p=0;
for(i=1;i<=m;i++)
if(gcd(i,m)==1)
num[++p]=i;
ret=k/p;
pos=k%p;
if(pos==0)
{
pos=p;
ret--;
}
ans=ret*m+num[pos];
printf("%I64d\n",ans);
}
}