Compution - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: Compution (/thread-17201.html) |
Compution - lekuru01 - Apr-02-2019 Good evening everyone, i m trying to compute GCD and LCM of n numbers and i can only do GCD and LCM for two integer numbers. I need your help and/or direction on this problem. while True: x=int(input('Enter a number:')) if x==0: break else: y=int(input('Enter a number:')) temp1= x temp2=y while temp2 !=0: t= temp2 temp2=temp1%temp2 temp1= t gcd = temp1 lcm = (x*y)/gcd print("GCD =",gcd) print("LCM =", int(lcm)) RE: Compution - scidam - Apr-02-2019 I think you can improve code I just wrote; it is about finding GCD of several values: def gcd(*x): """Returns greatest common divisor""" def _gcd2(x, y): # FIXME: ensuring that x > y should be moved somewhere else, e.g. in # decorator called ensure_sorted x, y = max(x, y), min(x, y) while True: a, b = divmod(x, y) x, y = y, b if b == 0: break return x if len(x) == 2: return _gcd2(*x) else: return _gcd2(x[0], gcd(*x[1:])) if __name__ == "__main__": print("Should return GCD of a set of numbers") print("Result of GCD(2, 4, 8) is ", gcd(2, 4, 8)) |