Consider the set of irreducible fractions A = {n/d | n≤d and d ≤ 10000 and gcd(n, d) = 1}. You are given a member of this set and your task is to find the largest fraction in this set less than the given fraction.
Note: This is a set and all the members are unique.
Examples:
Input: n = 1, d = 4
Output: {2499, 9997}
Explanation: 2499/9997 is the largest fraction.Input: n = 2, d = 4
Output: {4999, 9999}
Explanation: 4999/9999 is the largest fraction.
Approach: The solution to the problem is based on the following mathematical concept:
Say the desired fraction is p/q. So,
p/q < n/d
p < (n*q)/d
As we want p/q to be smaller than n/d, start to iterate over q from q = d+1.
Then for each value of q, the value of p will be floor((n*q)/d).
Follow the below steps to implement the above idea:
- Create two variables num and den to store the final answer. Initialize them as num =- 1 and den =1.
- Now, loop i from d+1 to 10000:
- Calculate the value of the fraction with denominator as i using the above observation.
- The numerator will be (n*i)/d [this is integer division here, i.e., it gives the floor value] and denominator = i+1
- If the fraction is greater than num/den, then update num and den accordingly.
- After all the iterations num and den will store the required numerator and denominator.
Below is the implementation of the above approach:
C++
|
2499 9997
Time Complexity: O(n)
Auxiliary Space: O(1)