I found a problem related to rational numbers.
Two rational numbers are given and the task is to find the simplest rational number between them.
For this problem, the simplicity of a rational number could be defined as the rational number with the smallest numerator, although I am open to other suggestions for this metric, e.g. similar question to Math stack exchange, if it makes the solution easier.
The sample inputs and output might be:
Inputs: 1110/416 and 1110/417, Output: 8/3
Inputs: 500/166 and 500/167, Output: 3/1
Any ideas or at least an advice on how to approach this problem? I'm struggling.
Thanks
EDIT:
Additional observations:
- Although there are infinitely many rational numbers between two given rational numbers, there are indeed finitely many rational numbers that are simpler than the two.
- The trivial solution could be just to try all combinations of numerator/denominator (ranging from 1 to the highest numerator or denominator respectively), reduce them, and see if the number is in between. I'm not sure what would be the O complexity of it, but I'd guess something like n2.
The relevant math is described in the Wikipedia article on continued fractions. In a nutshell, you compute the two continued fractions for the lower and upper endpoints and then try four combinations where the continued fraction is truncated after the common endpoint.
Here's a Python implementation.