Search code examples
mathlogicfractions

Return list of simplest fractions for a given number


I'm trying to create a function that will generate a list of all the simplest fractions for a given number. I'm not fussed about what language an example is given in, it's more the logic I'm trying to get my head around.

  • Example: 4
  • Correct: 1/4, 1/2, 3/4
  • Unnecessary: 1, 2/4

  • Example: 12

  • Correct: 1/12, 1/6, 1/4, 1/3, 5/12, 1/2, 7/12, 2/3, 3/4, 5/6, 11/12
  • Unnecessary: 1, 2/6, 4/6, 2/4, 6/12, 4/12, etc

I'm not sure if I'm heading in the right direction by iterating through every possible fraction or if there's a better way, or how to find the simplest expression of the fraction.

Pseudo code:

denominator = 12;
for (i = 1; i <= denominator; i++) {
    for (n = 1; n <= denominator; n++) {
        // find simplest expression of fraction when n!=i
    }
}

Any help would be greatly appreciated, thanks!


Solution

  • You don't need the inner for-loop, just a method to find the Greatest Common Divisor in order to reduce the fraction:

    int denominator = 12;
    for (int i = 1; i < denominator; i++) {  // note change from <= to <
        int gcd = GCD(i, denominator);
        // answer will be "{i/gcd}/{denominator/gcd}"
    }