Saturday, June 4, 2022
HomeWordPress DevelopmentDiscover the most important co-prime fraction lower than the given fraction

Discover the most important co-prime fraction lower than the given fraction


Enhance Article

Save Article

Like Article

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++

  

#embody <bits/stdc++.h>

utilizing namespace std;

  

vector<int> numAndDen(int n, int d)

{

    int num = -1, den = 1;

    vector<int> ans;

  

    

    for (int i = d + 1; i <= 10000; i++) {

        int x = (n * i) / d;

        if (1.0 * x / i > 1.0 * num / den

            and __gcd(x, i) == 1)

            num = x, den = i;

    }

    ans.push_back(num);

    ans.push_back(den);

    return ans;

}

  

int major()

{

    int n = 1, d = 4;

  

    

    vector<int> ans = numAndDen(n, d);

    for (auto i : ans)

        cout << i << " ";

    return 0;

}

Time Complexity: O(n)
Auxiliary Area: O(1)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments