You asked a question on a website where people usually provide code in their answers. There are no other answers with code, C and Java are not my specialty, and so here is some code in Python.
#! /usr/bin/env python3
import fractions
import functools
import math
def main():
f = fractions.Fraction(3, 4)
e = to_egyptian_fractions(f)
print(*e, sep=' + ')
f = fractions.Fraction(6, 7)
e = to_egyptian_fractions(f)
print(*e, sep=' + ')
f = fractions.Fraction(7654, 321)
e = to_egyptian_fractions(f)
print(*e, sep=' + ')
def validate(function):
@functools.wraps(function)
def wrapper(fraction):
total = fractions.Fraction(0)
for egyptian in function(fraction):
if 1 not in {egyptian.numerator, egyptian.denominator}:
raise AssertionError('function has failed validation')
yield egyptian
total += egyptian
if total != fraction:
raise AssertionError('function has failed validation')
return wrapper
@validate
def to_egyptian_fractions(fraction):
quotient = math.floor(fraction.numerator / fraction.denominator)
if quotient:
egyptian = fractions.Fraction(quotient, 1)
yield egyptian
fraction -= egyptian
while fraction:
quotient = math.ceil(fraction.denominator / fraction.numerator)
egyptian = fractions.Fraction(1, quotient)
yield egyptian
fraction -= egyptian
if __name__ == '__main__':
main()
Maybe others with find this to be useful as a simple guide while writing their own implementations. The program up above handles fractions with values greater than one and produces the following output.
1/2 + 1/4
1/2 + 1/3 + 1/42
23 + 1/2 + 1/3 + 1/92 + 1/29532
[math]
tag from this question which obviously has to do with math. I'm not math-illiterate. I'm 100% sure I removed the[artificial-intelligence]
flag. – Ivers[artificial-intelligence]
before I submitted my edit. – Ivers