Contemplate the set of irreducible fractions A = n≤d and d ≤ 10000 and gcd(n, d) = 1. You might be given a member of this set and your activity is to search out the most important fraction on this set lower than the given fraction.
Word: This can be a set and all of the members are distinctive.
Examples:
Enter: n = 1, d = 4
Output: {2499, 9997}
Clarification: 2499/9997 is the most important fraction.Enter: n = 2, d = 4
Output: {4999, 9999}
Clarification: 4999/9999 is the most important fraction.
Strategy: The answer to the issue is predicated on the next mathematical idea:
Say the specified fraction is p/q. So,
p/q < n/d
p < (n*q)/d
As we wish p/q to be smaller than n/d, begin to iterate over q from q = d+1.
Then for every worth of q, the worth of p will probably be flooring((n*q)/d).
Observe the under steps to implement the above concept:
- Create two variables num and den to retailer the ultimate reply. Initialize them as num =- 1 and den =1.
- Now, loop i from d+1 to 10000:
- Calculate the worth of the fraction with denominator as i utilizing the above commentary.
- The numerator will probably be (n*i)/d [this is integer division here, i.e., it gives the floor value] and denominator = i+1
- If the fraction is bigger than num/den, then replace num and den accordingly.
- After all of the iterations num and den will retailer the required numerator and denominator.
Beneath is the implementation of the above method:
C++
|
Time Complexity: O(n)
Auxiliary Area: O(1)