Simplified Fractions in C++

C++Server Side ProgrammingProgramming

Suppose we have an integer n, we have to find a list of all simplified fractions between 0 and 1 (exclusive) such that the denominator <= n. Here the fractions can be in any order.

So, if the input is like n = 4, then the output will be ["1/2","1/3","1/4","2/3","3/4"] as "2/4" is not a simplified fraction because it can be simplified to "1/2".

To solve this, we will follow these steps −

  • Define an array ret

  • for initialize i := 2, when i <= n, update (increase i by 1), do −

    • for initialize j := 1, when j < i, update (increase j by 1), do −

      • c := gcd of i and j

      • a := j / c

      • b := i / c

      • insert (a as string concatenate "/" concatenate b as string) at the end of ret

  • return an array of all unique elements present in ret

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<string> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<string> simplifiedFractions(int n) {
      vector<string> ret;
      for (int i = 2; i <= n; i++) {
         for (int j = 1; j < i; j++) {
            int c = __gcd(i, j);
            int a = j / c;
            int b = i / c;
            ret.push_back(to_string(a) + "/" + to_string(b));
         }
      }
      set<string> s(ret.begin(), ret.end());
      return vector<string>(s.begin(), s.end());
   }
};
main(){
   Solution ob;
   print_vector(ob.simplifiedFractions(4));
}

Input

4

Output

[1/2, 1/3, 1/4, 2/3, 3/4, ]
raja
Published on 17-Nov-2020 16:54:22
Advertisements