Last active
November 30, 2016 13:54
-
-
Save dividedharmony/5faedba9dcccf3d34c46d125f8b72efd to your computer and use it in GitHub Desktop.
Solve Egyptian Fractions using Fibonacci's Greedy Algorithm
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
class EgyptianFraction | |
class ImproperFraction < StandardError; end | |
attr_reader :converted_fractions, :original_rational, :current_rational | |
def initialize(numerator, denominator) | |
raise ImproperFraction if numerator > denominator | |
@converted_fractions = [] | |
@original_rational = Rational(numerator, denominator) | |
@current_rational = original_rational | |
end | |
def solve | |
@solved ||= convert_and_record | |
end | |
def to_r | |
original_rational | |
end | |
private | |
def convert_and_record | |
convert_subfractions | |
converted_fractions << current_rational | |
end | |
def convert_subfractions | |
until unit_fraction? | |
record_fraction(largest_subfraction) | |
end | |
end | |
def largest_subfraction | |
Rational(1, largest_subdenominator) | |
end | |
def largest_subdenominator | |
(current_rational.denominator.to_f / current_rational.numerator.to_f).ceil | |
end | |
def unit_fraction? | |
current_rational.numerator == 1 | |
end | |
def record_fraction(rational) | |
@current_rational -= rational | |
converted_fractions << rational | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment