-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
45 additions
and
27 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,26 +1,38 @@ | ||
""" | ||
Problem: | ||
The ancient Egyptians used to express fractions as a sum of several terms where each numerator is one. | ||
Create an algorithm to turn an ordinary fraction a / b, where a < b, into an Egyptian fraction. | ||
For example, 4 / 13 can be represented as 1 / 4 + 1 / 18 + 1 / 468. | ||
The ancient Egyptians used to express fractions as a sum of several terms where each | ||
numerator is one. For example, 4 / 13 can be represented as | ||
1 / (4 + 1 / (18 + (1 / 468))). | ||
Create an algorithm to turn an ordinary fraction a / b, where a < b, into an Egyptian | ||
fraction. | ||
""" | ||
|
||
from fractions import Fraction | ||
from math import ceil | ||
from typing import List | ||
|
||
|
||
def get_egyptian_frac( | ||
fraction: Fraction, previous_fraction: List[Fraction] = list() | ||
) -> List[Fraction]: | ||
if fraction.numerator == 1: | ||
previous_fraction.append(fraction) | ||
return previous_fraction | ||
|
||
egyptian_fraction = Fraction(1, ceil(fraction.denominator / fraction.numerator)) | ||
previous_fraction.append(egyptian_fraction) | ||
return get_egyptian_frac(fraction - egyptian_fraction, previous_fraction) | ||
|
||
|
||
def get_egyptian_frac(frac, prev_frac=list()): | ||
# base case for recursion | ||
if frac.numerator == 1: | ||
prev_frac.append(frac) | ||
return prev_frac | ||
# generating the next fraction | ||
egyptian_frac = Fraction(1, ceil(frac.denominator / frac.numerator)) | ||
prev_frac.append(egyptian_frac) | ||
# calling the function recursively | ||
return get_egyptian_frac(frac - egyptian_frac, prev_frac) | ||
if __name__ == "__main__": | ||
print(get_egyptian_frac(Fraction(4, 13))) | ||
|
||
|
||
# DRIVER CODE | ||
print(get_egyptian_frac(Fraction(4, 13))) | ||
""" | ||
SPECS: | ||
TIME COMPLEXITY: O(log(n)) | ||
SPACE COMPLEXITY: O(log(n)) | ||
""" |