Simplified Fractions - Problem

Given an integer n, your task is to find all simplified fractions between 0 and 1 (exclusive) where the denominator is less than or equal to n.

A simplified fraction is one where the numerator and denominator have no common factors other than 1 (i.e., their greatest common divisor is 1). For example, 2/4 is not simplified because both 2 and 4 are divisible by 2, but 1/2 is simplified.

Examples:

  • For n = 2: Valid fractions are 1/2
  • For n = 3: Valid fractions are 1/2, 1/3, 2/3
  • For n = 4: Valid fractions are 1/2, 1/3, 1/4, 2/3, 3/4 (note: 2/4 is excluded as it's not simplified)

Return the fractions as strings in the format "numerator/denominator". The order of the result doesn't matter.

Input & Output

example_1.py โ€” Basic Case
$ Input: n = 2
โ€บ Output: ["1/2"]
๐Ÿ’ก Note: For denominator 2, only numerator 1 is valid since 1 < 2 and GCD(1,2) = 1
example_2.py โ€” Multiple Fractions
$ Input: n = 3
โ€บ Output: ["1/2","1/3","2/3"]
๐Ÿ’ก Note: For denominator 2: 1/2 is valid. For denominator 3: both 1/3 and 2/3 are valid since GCD(1,3)=1 and GCD(2,3)=1
example_3.py โ€” With Non-simplified Fraction
$ Input: n = 4
โ€บ Output: ["1/2","1/3","1/4","2/3","3/4"]
๐Ÿ’ก Note: All fractions from previous examples plus 1/4 and 3/4. Note that 2/4 is excluded because GCD(2,4)=2โ‰ 1, so it's not simplified

Constraints

  • 1 โ‰ค n โ‰ค 100
  • The output can be in any order
  • All fractions must be in simplified form

Visualization

Tap to expand
Simplified Fractions: Step-by-Step ProcessStep 1:Generate AllStep 2:Check GCDStep 3:Collect ValidExample with n=4:Candidates: 1/2, 2/2, 1/3, 2/3, 1/4, 2/4, 3/4After GCD check:โœ“ 1/2 (GCD=1), 1/3 (GCD=1), 2/3 (GCD=1), 1/4 (GCD=1), 3/4 (GCD=1)โœ— 2/2 (GCD=2), 2/4 (GCD=2)Result: ["1/2", "1/3", "1/4", "2/3", "3/4"]
Understanding the Visualization
1
Generate candidates
Create all possible fractions with denominators 2 through n
2
Apply GCD test
For each fraction, check if GCD(numerator, denominator) equals 1
3
Collect results
Keep only fractions that pass the GCD test (simplified fractions)
4
Format output
Convert to string format 'numerator/denominator'
Key Takeaway
๐ŸŽฏ Key Insight: A fraction a/b is in its simplest form if and only if GCD(a,b) = 1, meaning they share no common factors other than 1.
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
26.8K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen