Advertisement
brilliant_moves

LCM.py

May 14th, 2018
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. #LCM.py by Chris Clarke
  2. #Python3
  3. #14.05.2018
  4.  
  5. """
  6. Asked on Yahoo! Answers:
  7. How can i find lcm of n numbers in python without using any builtin
  8. function and also not using recursion function?
  9. """
  10.  
  11. """greatest common divisor"""
  12. def gcd (a, b):
  13.     while b != 0:
  14.         t = b
  15.         b = a % b
  16.         a = t
  17.     return a
  18.  
  19. """least common multiple"""
  20. def lcm (a, b):
  21.     r = gcd (a, b)
  22.     return a // r * b
  23.  
  24. def main():
  25.    print ("Program to find the least common multiple of N numbers.")
  26.    n = []
  27.    while True:
  28.       a = int (input ("Enter a number: (-1 to quit) : "))
  29.       if a >= 0:
  30.          n.append (a)
  31.       else:
  32.          break
  33.  
  34.    result = n[0]
  35.    for x in range (1, len (n)):
  36.       result = lcm (result, n[x])
  37.  
  38.    print ("The LCM of {0} is {1}" .format (n, result))
  39.  
  40. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement