least common multiple

/ Published in: Python
Save to your folder(s)

Calculates the lcm of 2 or more numbers (based on a self-made algorithm)

Copy this code and paste it in your HTML
  1. def lcm(*args):
  2. """Calculates lcm of args"""
  3. #find the largest of numbers:
  4. biggest = max(args)
  5. #the list of the numbers without the largest:
  6. rest = [n for n in args if n != biggest]
  7. #the factor is to multiply with the biggest as long as the result of them is not divisble by all of the numbers in the rest:
  8. factor = 1
  9. while True:
  10. #check if biggest is divisble by all in the rest:
  11. ans = False in [(biggest * factor) % n == 0 for n in rest]
  12. #if so the clm is found: break the loop and return it, otherwise increment the factor by 1 and try again:
  13. if not ans:
  14. break
  15. factor += 1
  16. biggest *= factor
  17. return "lcm of {0} is {1}".format(args, biggest)

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.