1. Brute Force — Linear Denominator Scan
Intuition
Test integers d = 2, 3, 4, ... sequentially. If 1/d <= nr/dr, append d, subtract 1/d from current fraction, and continue with d + 1.
When to apply: When denominators are very small.
Algorithm
- Step 1: Initialize d = 2, result = [].
- Step 2: While nr > 0: if dr <= nr * d, append d and update nr = nr * d - dr, dr = dr * d.
- Step 3: Increment d++.
- Step 4: Return result.
#include <iostream>#include <vector>#include <numeric> using namespace std; class Solution { long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); }public: vector<long long> egyptianFraction(long long nr, long long dr) { vector<long long> res; long long d = 2; while (nr > 0) { if (dr <= nr * d) { res.push_back(d); nr = nr * d - dr; dr = dr * d; long long g = gcd(nr, dr); nr /= g; dr /= g; } d++; } return res; }}; int main() { Solution sol; auto res = sol.egyptianFraction(2, 3); for (auto d : res) cout << d << " "; cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(dr * steps)— Linear increment of d until matching denominator. - Space complexity:
O(steps)— Result array storage.
Why Brute Force Doesn't Scale:
Linear stepping from 2 upwards times out for denominators in the thousands. Greedy jumping to ceil(dr / nr) takes logarithmic steps.
For 6/14: takes only 3 steps [3, 11, 231] instead of checking 231 numbers.