Skip to content

Instantly share code, notes, and snippets.

@phillipkent
Created March 29, 2013 11:17
Show Gist options
  • Save phillipkent/5270266 to your computer and use it in GitHub Desktop.
Save phillipkent/5270266 to your computer and use it in GitHub Desktop.
Greedy algorithm for Egyptian fractions
# Greedy Algorithm for Egyptian Fractions
# To express a / b as a sum of unit fractions (1 / c_1) + ... + (1 / c_n)
def main():
print("*** Greedy algorithm for Egyptian fractions ***\n")
while 1:
try:
a = int(input("Enter a: "))
b = int(input("Enter b: "))
result = iterate(a,b)
print(map(prettyfrac,result))
except TypeError:
print("Invalid input (both must be integers).")
continue
except ValueError:
print("Exiting.")
return
def iterate(a, b):
"""generate sequence of unit fractions."""
l = []
while 1:
if b%a == 0: # a divides into b so already a unit fraction
l.append(b/a)
return l
else:
aa = b/a + 1
l.append(aa)
a = a*(lcm(b,aa)/b) - (lcm(b,aa)/aa)
b = lcm(b,aa)
def gcd(a, b):
"""greatest common divisor of two integers"""
if b == 0:
return a
return gcd(b, a % b)
def lcm(a, b):
"""lowest common multiple of two integers"""
return a * b / gcd(a, b)
def prettyfrac(z):
return "1/"+str(z)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment