Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Compution
#1
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))
Reply
#2
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))
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020