Python is an example of finding the least common multiple and the most common divisor based on recursive algorithm

  • 2020-11-25 07:21:54
  • OfStack

In this paper, Python is used to calculate the least common multiple and the most common divisor based on recursive algorithm. To share for your reference, the details are as follows:


#  Least common multiple 
def lcm(a, b, c=1):
  if a * c % b != 0:
    return lcm(a, b, c+1)
  else:
    return a*c
test_cases = [(4, 8), (35, 42), (5, 7), (20, 10)]
for case in test_cases:
  print('lcm of {} & {} is {}'.format(*case, lcm(*case)))
def lcm(a, b):
  for i in range(2, min(a,b)+1):
    if a % i == 0 and b % i == 0:
      return i * lcm(a//i, b//i)
  else:
    return a*b
test_cases = [(4, 8), (5, 7), (24, 16), (35, 42)]
for case in test_cases:
  print('lcm of {} & {} is {}'.format(*case, lcm(*case)))
#  Maximum common divisor 
def gcd(a, b):
  if a == b:
    return a
  elif a-b > b:
    return gcd(a-b, b)
  else:
    return gcd(b, a-b)
test_cases = [(35, 14), (88, 66), (5, 4), (20, 10)]
for case in test_cases:
  print('GCD of {} & {} is {}'.format(*case, gcd(*case)))

Operation results:

[

lcm of 4 & 8 is 8
lcm of 35 & 42 is 210
lcm of 5 & 7 is 35
lcm of 20 & 10 is 20
GCD of 35 & 14 is 7
GCD of 88 & 66 is 22
GCD of 5 & 4 is 1
GCD of 20 & 10 is 10

]

PS: Here is another online tool related to this site for your reference:

Online least common Multiple/maximum common divisor calculation tool:
http://tools.ofstack.com/jisuanqi/gbs_gys_calc

For more information about Python, please refer to the following topics: Summary of Python Mathematical Operation Skills, Python Data Structure and Algorithm Tutorial, Python Function Skills Summary, Python String Operation Skills Summary, Python Introductory and Advanced Classic Tutorial and Python File and Directory Operation Skills Summary.

I hope this article is helpful for Python programming.


Related articles: