用贪心做
初始i=j=1
当i/j>=n/m时:j++
反之i++
随时记录最接近的值即可
View Code
#include<stdio.h>
double jue(double a)
{
if(a>0)return a;
return -a;
}
int main()
{
int n,m;
while(scanf("%d %d",&n,&m)!=EOF)
{
int ri,rj,i,j;
double e=n*1.0/m,t,cha=99999999;
i=1;
j=1;
while(i<=32767&&j<=32767)
{
t=i*1.0/j;
if(t>=e)
j++;
else
i++;
t=i*1.0/j;
t=jue(t-e);
if(t<cha&&(i*m!=j*n)&&i<=32767&&j<=32767)
{
cha=t;
ri=i;
rj=j;
}
}
printf("%d %d\n",ri,rj);
}
return 0;
}
double jue(double a)
{
if(a>0)return a;
return -a;
}
int main()
{
int n,m;
while(scanf("%d %d",&n,&m)!=EOF)
{
int ri,rj,i,j;
double e=n*1.0/m,t,cha=99999999;
i=1;
j=1;
while(i<=32767&&j<=32767)
{
t=i*1.0/j;
if(t>=e)
j++;
else
i++;
t=i*1.0/j;
t=jue(t-e);
if(t<cha&&(i*m!=j*n)&&i<=32767&&j<=32767)
{
cha=t;
ri=i;
rj=j;
}
}
printf("%d %d\n",ri,rj);
}
return 0;
}