Last Updated: 19 Apr, 2021

Simplified Fractions

Easy
Asked in company
alibaba

Problem statement

You are given an integer ‘N’. Your task is to find all “simplified fractions” in the range [0, 1] whose denominator is less than or equal to ‘N’.

Note:

1. A “fraction” is not a whole number. It is a part of a whole.
2. When the numerator and denominator of a fraction are no longer to be reduced to any smaller number upon division by any common integer, the fraction is known as a “simplified fraction”. 
3. For example, 1/2 is a simplified fraction but 2/4 is not a simplified fraction as we can reduce 2/4 to 1/2. 
Input Format:
The first line contains an integer ‘T’, which denotes the number of test cases to be run. Then, the T test cases follow. 

The first and only line of each test case contains an integer, ‘N’, as described in the problem statement.
Output Format:
For each test case, print the “list of strings representing all simplified fractions”, as described in the problem statement. If there are no such fractions, then print ‘-1’ without any quotes.

Output for each test case will be printed in a separate line.
Note:
1. You do not need to print anything. It has already been taken care of. Just implement the given function.

2. You can return the list in “any order”. 
Constraints:
1 <= ‘T’ <= 10
1 <= ‘N’ <= 100

Time Limit: 1 sec

Approaches

01 Approach

  • First, let us try to understand the “simplified fraction”. If there are no such integers available that can divide both the numerator and denominator, then the fraction is called a simplified fraction. In other words, if the Greatest Common Divisor (GCD) of the numerator and the denominator is ‘1’, then the fraction is a “simplified fraction”.
  • Another condition is that we want the denominator to be less than or equal to ‘N’, and we know that to be a valid fraction the numerator must be less than the denominator.
  • This can conclude the logic part, what remains is only the implementation.


 

  • If 'N' == 1, then no valid fractions available. So, return “-1”.
  • Create an empty list to store the simplified fractions, let it be 'ANS'.
  • Run a loop from 'NUMERATOR' = 1 to 'NUMERATOR' < 'N', in each iteration:
    • Run a loop from 'DENOMINATOR' = 'NUMERATOR' + 1 to 'DENOMINATOR' <= 'N', in each iteration:
      • If the gcd('DENOMINATOR', 'NUMERATOR') == 1, then add a string “NUMERATOR/DENOMINATOR” to the 'ANS'.

Finally, return the 'ANS'.