給出一個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 +1;
return ;
}
ll t = min(y/x, b/a);
calc(y-t*x, x, b-t*a, a , q, p);
q += t*p;
return ;
}
int main()
{
freopen("baseball.in","r",stdin);
freopen("baseball.out","w",stdout);
while (~scanf("%d 0.%lld", &n, &r))
{
if (r==0) {
printf("%d\n",1);continue;
}
ll v = 1;
for(int i = 0; i<=n; ++i) v*=10;
ll a = r*10-5; ll b = v;
while (a%5==0 && b%5==0) a/=5, b/=5;
ll x = r*10+5; ll y = v;
while (x%5==0 && y%5==0) x/=5, y/=5;
calc(a,b,x,y,p,q);
printf("%lld\n",b<q?b:q);
}
return 0;
}