您的位置:首页 > 移动开发

poj 2773 Happy 2006解题报告 <欧拉函数>

2012-02-24 19:59 471 查看
链接:http://poj.org/problem?id=2773DescriptionTwo 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.
InputThe input contains multiple test cases. For each test case, it contains two integers m (1 <= m <= 1000000), K (1 <= K <= 100000000).
OutputOutput the K-th element in a single line.
Sample Input
2006 1
2006 2
2006 3

Sample Output
1
3
5

题意:输入 M K 求第 K 个与 M 互素的数

思路:因为 gcd( a, b ) == gcd( a+k*b, b ), 所以可以先用欧拉函数求出 M 内所有与 M 互素的数的个数再暴力搜索

欧拉函数:/article/6404988.html

代码:
#include <stdio.h>
#include <string.h>
int gcd( int a, int b )
{
return b==0?a:gcd( b, a%b );
}

int Eular( int a )
{
int l=1;
for( int i=2; i*i<=a; ++i )
{
if( a%i==0 )
{
l *= ( i-1 );
a /= i;
while( a%i==0 )
{
l *= i;
a /= i;
}
}
}
if( a>1 )
l*=(a-1);
return l;
}

int main( )
{
int M, K;
while( scanf( "%d%d", &M, &K ) != EOF )
{
if( M==1 )
{
printf("%d\n", K );
continue;
}
int k=Eular(M);
int t=K%k;
if( t )
{
int n=0;
for( int i=1; ;++i   )
{
if( gcd( M, i )==1 )
{
n++;
}
if( n==t )
{
printf( "%d\n",K/k*M+i );
break;
}
}
}
else
{
printf("%d\n", (K/k)*M-1 );
}
}
return 0;
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: