VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-closest-fraction-to-given-fraction-having-minimum-absolute-difference/

⇱ Find the closest Fraction to given fraction having minimum absolute difference - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the closest Fraction to given fraction having minimum absolute difference

Last Updated : 23 Jul, 2025

Given three integers x, y, and n, the task is to find such a pair of integers a, ?b (1?<=?b?<=?n; 0?<=?a) that the value |x/y - a/b| is as minimal as possible, where |x| represents the absolute value of x.

Examples:

Input: x = 3, y = 7, n = 6
Output: 2/5
Explanation: a=2 and b=5 and b<=6 then 3/7 - 2/5 = 1/35, which is the minimum difference possible

Input: x = 12, y = 37, n = 5
Output: 1/3

Approach: Iterate over the denominator. Let the denominator be i. Then it is required to choose such a numerator d such that |x/y - d/i| is minimal. d = (x*i)/y is a good choice. Also check for d+1. While updating the answer from A/B to d/i, check if x/y - d/i < x/y -A/B or (B*x-y*A) * (i*y) > (i*x-y*d) * (B*y). Follow the steps below to solve the problem:

  • Initialize the variables A and B as -1 to store the answers.
  • Iterate over the range [1, N] using the variable i and perform the following steps:
    • Initialize the variable d as (i*x)/y as the closest possible numerator.
    • If d is greater than equal to 0 and A is equal to -1 or ABS(B * x - y * A) * ABS(i * y) is greater than ABS(i * x - y * d) * ABS(B * y), then set the value of A as d and B as i.
    • Increase the value of d by 1.
    • If d is greater than equal to 0 and A is equal to -1 or ABS(B * x - y * A) * ABS(i * y) is greater than ABS(i * x - y * d) * ABS(B * y), then set the value of A as d and B as i.
  • After performing the above steps, print the value of A/B as the answer.

Below is the implementation of the above approach.


Output
2/5

Time Complexity: O(N)
Auxiliary Space: O(1)

Comment
Article Tags: