/***** rational neighbor problem input int a, b in [1,100000] float n in [.00000001, .1] output int c, d such that 0 < c/d - a/b <= n and d is the minimal denominator with this property. ******/ /* Thoughts: iff 0 < cb - ad <= nbd implies bd >= 1/n so that nbd >= 1 range of 1/n is [10, 10^8] continued fraction approximation probably gets it. brute force search may work fast enough (3 sec) for d = 1 to 100000 find least c such that a/b < c/d, bail (done) if 0 < c/d - a/b <= n return c,d translation of find: ad < bc. c = ceil(ad/b); translation of condition: c <= nd possible speedup: binary search for d. */ #include #include using namespace std; void ratnbr(int a, int b, float n, int& c, int& d) { double a_b = a; a_b /= b; double delta; d = 0; do { ++d; double x; x = a*d; x /= b; c = ceil(x); double c_d = c; c_d /= d; delta = c_d - a_b; if (delta == 0) { ++c; c_d = c; c_d /= d; delta = c_d - a_b; } } while (delta > n); return; } /* stub version used for initial test of main() void ratnbr(int a, int b, float n, int& c, int& d) { c = a; d = b; return; } */ int main () { int a, b, c, d; float n; while (cin >> a >> b >> n) { ratnbr(a, b, n, c, d); cout << c << " " << d << endl; } }