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