In this article, an example of Python custom function to achieve the greatest common denominator, the least common multiple of two numbers. Shared for your reference, as follows:
1. Algorithm for finding the least common multiple.
Least common multiple = product of two integers / greatest common divisor
So we first find the greatest common divisor of two integers, the idea of finding the greatest common divisor of two numbers is as follows.
2. Algorithm for finding the greatest common divisor.
① Integer A is rounded to the nearest integer B, and the remainder is expressed as an integer C. Example: C = A % B
② If C is equal to 0, then C is the greatest common divisor of integers A and B.
③ If C is not equal to 0, assign B to A, assign C to B, and then do steps 1 and 2 until the remainder is 0, then we know the greatest common divisor.
3. The program code is implemented as follows.
#!/usr/bin/env python # coding:utf-8 def fun(num1, num2): # Define a function with two formal parameters. if num1 < num2: # Read the size of two integers in order to use the larger number as the divisor and the smaller as the divisor. num1, num2 = num2, num1 # If the if condition is met, exchange values vari1 = num1 * num2 # Calculate the product of two integers, so that you can calculate the least common multiple later. vari2 = num1 % num2 # Taking the remainder of 2 integers while vari2 != 0: # Determine if the remainder is 0, if not, enter the loop. num1 = num2 # Re-assign the value for the next calculation num2 = vari2 vari2 = num1 % num2 # Taking the remainder of the reassigned two integers # Until vari2 equals 0, then we exit the loop at the most common denominator. vari1 /= num2 # To get the least common multiple print("The greatest common divisor is :%d" % num2) # Output print("The least common multiple is :%d" % vari1) # Output fun(6, 9)
Run results:
The greatest common divisor is: 3
The least common multiple is: 18
Screenshots of the run results:
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.