![]() |
VOOZH | about |
Every positive fraction can be represented as sum of unique unit fractions. A fraction is unit fraction if numerator is 1 and denominator is a positive integer, for example 1/3 is a unit fraction. Such a representation is called Egyptian Fraction as it was used by ancient Egyptians.
Following are a few examples:
Egyptian Fraction Representation of 2/3 is 1/2 + 1/6 Egyptian Fraction Representation of 6/14 is 1/3 + 1/11 + 1/231 Egyptian Fraction Representation of 12/13 is 1/2 + 1/3 + 1/12 + 1/156
We can generate Egyptian Fractions using Greedy Algorithm. For a given number of the form 'nr/dr' where dr > nr, first find the greatest possible unit fraction, then recur for the remaining part. For example, consider 6/14, we first find ceiling of 14/6, i.e., 3. So the first unit fraction becomes 1/3, then recur for (6/14 - 1/3) i.e., 4/42.
Below is the implementation of the above idea.
Egyptian Fraction representation of 6/14 is 1/3 + 1/11 + 1/231
Time complexity: The time complexity of the given algorithm depends on the value of the input fraction. In the worst case, the algorithm will run for O(d) iterations, where d is the denominator of the input fraction. Therefore, the time complexity of the algorithm is O(d).
Auxiliary Space:The space complexity of the given algorithm is O(1) as it uses only a fixed amount of extra space to store the variables used in the algorithm, regardless of the input size.
The recursive solution in Python is as follows:
1/3 + 1/11 + 1/231
Time complexity The time complexity of the given code is O(N^2), where N is the maximum number of denominators in the Egyptian fraction representation of the given fraction. This is because the algorithm recursively calculates each denominator in the fraction representation, and each recursive call takes O(N) time.
Space complexity :The space complexity of the given code is O(N), where N is the maximum number of denominators in the Egyptian fraction representation of the given fraction. This is because the algorithm uses a vector to store the denominators, which can have at most N elements.
The Greedy algorithm works because a fraction is always reduced to a form where denominator is greater than numerator and numerator doesn't divide denominator. For such reduced forms, the highlighted recursive call is made for reduced numerator. So the recursive calls keep on reducing the numerator till it reaches 1.