SoFunction
Updated on 2024-10-29

Python recursive and non-recursive algorithms to find the greatest common divisor, least common multiple of two numbers example

This article is an example of Python based on recursive and non-recursive algorithms to find the greatest common denominator, least common multiple of two numbers. Shared for your reference, as follows:

The concept of the greatest common divisor and the least common multiple are all very familiar with, here will not say more, today this is because of the problems encountered so write down as a record, but also hope to help others, the following code:

#!/usr/bin/env python
#coding:utf-8
from fractions import gcd
# Non-recursive implementation
def gcd_test_one(a, b):
  if a!=0 and b!=0:
    if a>b:
      a, b=b, a
    if b%a==0:
      return a
    gcd_list=[]
    for i in range(1,a):
      if b%i==0 and a%i==0:
        gcd_list.append(i)
    return max(gcd_list)
  else:
    print 'Number is wrong!!!'
# Recursive implementation
def gcd_test_two(a, b):
  if a>b:
    a, b=b, a
  if b%a==0:
    return a
  else:
    return gcd_test_two(a,b%a)
#python comes with gcd
def gcd_test_three(a, b):
  return gcd(a,b)
if __name__ == '__main__':
  print gcd_test_one(12,24)
  print gcd_test_one(12,8)
  print gcd_test_one(6,24)
  print gcd_test_one(0,24)
  print '----------------------------------------------------------------------------'
  print gcd_test_two(12,24)
  print gcd_test_two(12,8)
  print gcd_test_two(6,32)
  print '----------------------------------------------------------------------------'
  print gcd_test_three(12,24)
  print gcd_test_three(12,8)

The results are as follows:

12
4
6
Number is wrong!!!
None
----------------------------------------------------------------------------
12
4
2
----------------------------------------------------------------------------
12
4

PS: Here again for you to recommend a site related online tools for your reference:

Online least common multiple/maximum common denominator calculator:
http://tools./jisuanqi/gbs_gys_calc

Readers interested in more Python related content can check out this site's topic: theSummary of Python mathematical operations techniques》、《Python Data Structures and Algorithms Tutorial》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Python introductory and advanced classic tutorialsand theSummary of Python file and directory manipulation techniques

I hope that what I have said in this article will help you in Python programming.