Happy 2006 - POJ 2773 欧几里得

来源:互联网 发布:scala 与java混合编程 编辑:程序博客网 时间:2024/06/05 16:00

Happy 2006
Time Limit: 3000MS Memory Limit: 65536KTotal 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. 

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 12006 22006 3

Sample Output

135

题意:求第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);    }}



0 0
原创粉丝点击