acclivity

pyLeastCommonMultiple

Feb 21st, 2021 (edited)
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. # Find Least Common Multiple (LCM) from a list of integers
  2. # Mike Kerry - Feb 2021 - acclivity2@gmail.com
  3.  
  4. def find_lcm(inlist):
  5.     big = max(inlist)       # find the biggest integer from the provided list
  6.  
  7.     # Compute the product of all integers in the list.
  8.     # This will provide the upper limit for our LCM search
  9.     limit = 1
  10.     for m in inlist:
  11.         limit *= m
  12.  
  13.     # make "n" cycle through a range up to and including the limit, in steps of the biggest integer
  14.     # This loop is guaranteed to find the LCM, even if the only Common Multiple equals "limit"
  15.     for n in range(big, limit+1, big):
  16.         for x in inlist:                # See if all integers in the input list divide cleanly into n
  17.             if n % x:                   # if there was a remainder from the division ...
  18.                 break                   # ... then exit from this inner loop. "n" is not the LCM
  19.  
  20.         else:                           # If the inner loop completed successfully without "break" ...
  21.             return n                    # ... then we have found the LCM
  22.         # otherwise we continue executing the outer "for" loop to get the next value of "n"
  23.  
  24.     return None             # This statement will not be executed. It is only here to avoid Pycharm warnings
  25.  
  26.  
  27. tests = [[6, 9], [4, 6, 8], [7, 11, 13], [2, 17, 5, 6, 9]]
  28.  
  29. for t in tests:
  30.     lcm = find_lcm(t)
  31.     print("The LCM of ", t, "is", lcm)
  32.  
  33.  
  34. # Output:
  35. # The LCM of  [6, 9] is 18
  36. # The LCM of  [4, 6, 8] is 24
  37. # The LCM of  [7, 11, 13] is 1001
  38. # The LCM of  [2, 17, 5, 6, 9] is 1530
  39.  
Add Comment
Please, Sign In to add comment