Saturday, January 28, 2017

Finding the LCM and GCD of multiple numbers in python


Finding GCD of Multiple numbers:

#!/usr/bin/python



# finding gcd for two numbers

def gcd(x, y):

    while y != 0:

        (x, y) = (y, x % y)

    return x
if __name__ == '__main__':
 numbers= []
 count = input("how many numbers")
 for i in range (0, count):
  number = input("enter the number %d  " %(i+1))
  numbers.append(number)
 sorted_num = sorted(numbers)
 gcd_val = sorted_num[0]

 for i in range(1,count):
  gcd_val = gcd(gcd_val,sorted_num[i])


print "gcd value= %d" %gcd_val
Finding LCM values

def lcm(x, y):
   """This function takes two
   integers and returns the L.C.M."""

   # choose the greater number
   if x > y:
       greater = x
   else:
       greater = y

   while(True):
       if((greater % x == 0) and (greater % y == 0)):
           lcm = greater
           break
       greater += 1

   return lcm


if __name__ == '__main__':
  numbers= []
  count = input("how many numbers")
  for i in range (0, count):
    number = input("enter the number %d  " %(i+1))
    numbers.append(number)
 
  lcm_val = numbers[0]

  for i in range(1,count):
    lcm_val = lcm(lcm_val,numbers[i])


print "lcm value= %d" %lcm_val



No comments:

Post a Comment