题目大意
在给定范围内找到两个数,使其相除后的商最接近给定的小数
法里数列
引入法里数列
的概念,
每一行从0/1开始,以1/1结尾,其它数自左至右将所有的真分数按增加顺序排列;第n行是由所有分母小于或等于n的真分数组成,我们称为n阶法里数列
本题则是通过类似二分的方法,一阶一阶的跑法里数列中越来越趋近给定小数的项
AC代码(非原创)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;
int FindBestRat(double in_x, int maxdenom, int *pp, int *pq)
{
int p, q, bestp, bestq;
double cur, besterr;
bestq = maxdenom/2;
cur = ((double)bestq)*in_x;
bestp = (int)(cur + 0.5);
cur = ((double)bestp)/((double)bestq);
besterr = fabs(in_x - cur);
for(q = bestq+1; q <= maxdenom; q++) {
cur = ((double)q)*in_x;
p = (int)(cur + 0.5);
cur = ((double)p)/((double)q);
cur = fabs(in_x - cur);
if(cur < besterr){
bestp = p;
bestq = q;
besterr = cur;
}
}
p = __gcd(bestp, bestq);
*pp = bestp/p;
*pq = bestq/p;
return 0;
}
int main()
{
int nprob, curprob, index, maxdenom, p, q;
double dval;
if(scanf("%d", &nprob) != 1)
{
fprintf(stderr, "Scan failed on problem count\n");
return -2;
}
for(curprob = 1; curprob <= nprob ; curprob++)
{
// get prob num and sequence index
if(scanf("%d %d %lf", &index, &maxdenom, &dval) != 3)
{
fprintf(stderr, "scan failed on problem data problem index %d\n",
curprob);
return -6;
}
if(FindBestRat(dval, maxdenom, &p, &q) == 0) {
printf("%d %d/%d\n", curprob, p, q);
}
}
return 0;
}