Simplified Fractions
MediumUpdated: Aug 2, 2025
Practice on:
Problem
Given an integer n, return _a list of allsimplified fractions between _0 and1 (exclusive) such that the denominator is less-than-or-equal-ton. You can return the answer in any order.
Examples
Example 1
Input: n = 2
Output: ["1/2"]
Explanation: "1/2" is the only unique fraction with a denominator less-than-or-equal-to 2.
Example 2
Input: n = 3
Output: ["1/2","1/3","2/3"]
Example 3
Input: n = 4
Output: ["1/2","1/3","1/4","2/3","3/4"]
Explanation: "2/4" is not a simplified fraction because it can be simplified to "1/2".
Constraints
1 <= n <= 100
Solution
Method 1 – Brute Force with GCD
Intuition
For each denominator d from 2 to n, and numerator num from 1 to d-1, if gcd(num, d) == 1, the fraction is simplified.
Approach
- For each denominator d from 2 to n:
- For each numerator num from 1 to d-1:
- If gcd(num, d) == 1, add "num/d" to the result.
- For each numerator num from 1 to d-1:
Code
C++
#include <vector>
#include <string>
#include <numeric>
using namespace std;
class Solution {
public:
vector<string> simplifiedFractions(int n) {
vector<string> res;
for (int d = 2; d <= n; ++d) {
for (int num = 1; num < d; ++num) {
if (gcd(num, d) == 1)
res.push_back(to_string(num) + "/" + to_string(d));
}
}
return res;
}
};
Java
import java.util.*;
class Solution {
public List<String> simplifiedFractions(int n) {
List<String> res = new ArrayList<>();
for (int d = 2; d <= n; ++d) {
for (int num = 1; num < d; ++num) {
if (gcd(num, d) == 1)
res.add(num + "/" + d);
}
}
return res;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
}
Python
from math import gcd
class Solution:
def simplifiedFractions(self, n):
res = []
for d in range(2, n+1):
for num in range(1, d):
if gcd(num, d) == 1:
res.append(f"{num}/{d}")
return res
Complexity
- ⏰ Time complexity:
O(n^2)— For each denominator, check all numerators. - 🧺 Space complexity:
O(n^2)— For the result list.