给出一个n为小数,求一个分母最小的分数,使得它保留小数点后n位(四舍五入)为r。
给出r,显然四舍五入能为r的必然在区间[r-5*(-n-1),r+5*(-n-1))。
首先区间的两头都是分数,不妨设为a/b 和 x/y 现在就是求两个分数见分母最小的分数。
不妨设分母最小的分数为 p/q
a/b < p/q < x/y
若存在k,使得 y/x <k < b/a 那么 可以另 q= y/x+1,同时求出p,否则 必然有 0<= (y- t * x)/x < (q-p*t)/p < (b-a*t)/a <1 (t= min(y/x,b/a))
然后递归求出p和q就可以了。
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
ll r,p,q;
int n;
void calc(ll a, ll b , ll x, ll y, ll &p , ll &q)
{
if (a==0) {
p = 1; q = y/x+1; return ;
}
ll k = y/x+1;
if (k * a < b){
q = y/x+1; p = a * q / b +