Advertisement
warlock3301

LCM

Dec 16th, 2019
450
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. import math
  4.  
  5. print("""Select one option:
  6. 1. LCM of integers from 1 to user-defined N.
  7. 2. LCM of integers in a user-defined range.
  8. 3. LCM of a set of user-defined integers.
  9. """)
  10. choice = str(input('Input: '))
  11.  
  12.  
  13. def calc_lcm(arr):
  14. lcm = arr[0]
  15.  
  16. for i in arr[1:]:
  17. lcm = int(lcm * i / math.gcd(lcm, i))
  18.  
  19. return lcm
  20.  
  21.  
  22. if choice == '1':
  23. in_num = int(input('Upper bound: '))
  24.  
  25. arr = []
  26.  
  27. for i in range(in_num):
  28. arr.append(i+1)
  29.  
  30. lcm = calc_lcm(arr)
  31. print(f'LCM integers from 1 to {in_num} = {lcm}')
  32. elif choice == '2':
  33. lower_bound = int(input('Lower bound: '))
  34. upper_bound = int(input('Upper bound: '))
  35.  
  36. arr = list(range(lower_bound, (upper_bound + 1)))
  37.  
  38. lcm = calc_lcm(arr)
  39.  
  40. print(f'LCM of integers from {lower_bound} to {upper_bound} = {lcm}')
  41. elif choice == '3':
  42. arr = []
  43.  
  44. while True:
  45. try:
  46. arr.append(int(input('Enter an integer or type "c" to quit and calculate LCM: ')))
  47. except ValueError:
  48. break
  49.  
  50. lcm = calc_lcm(arr)
  51.  
  52. out_num = ','.join(str(x) for x in arr)
  53. print(f'LCM of ({out_num}) = {lcm}')
  54. else:
  55. print('Select between options 1, 2 and 3.')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement