Best Rational Approximation
Jump to navigation
Jump to search
This problem asks for the best fractional representation of a floating point number less than 1, with a specified denominator maximum.
The maximum denominator is 10^5, so we can try every denominator. You can either just multiply the input number by the denominator and try the two possible numerators around that, or if you're really bored, you could binary search.
You could also start with 0/1, and if the resulting quotient is less than the target, add 1 to the numerator...else add 1 to the denominator. Return whatever comes out best, being sure to check +-1 when you hit the maximum denominator just to be sure you didn't miss an edge case.
Be sure your answer is in lowest terms.