Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to find the maximum common divisor in Python

Shulou Source: shulou.com Published: 2022-06-02 08:16:51 09月26日 Update

Today, I will talk to you about how to find the maximum common divisor in Python. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.

Code implementation

# define a function def hcf (x, y): "this function returns the maximum common divisor of two numbers"# get the minimum value if x > y: smaller = y else: smaller = x for i in range (1) Smaller + 1): if ((x% I = = 0) and (y% I = = 0): hcf = I return hcf# user enters two digits num1 = int ("enter the first number:") num2 = int (input ("enter the second number:") print (num1, "and", num2, "the greatest common divisor is", hcf (num1, num2)

The result of running the program:

Enter the first number: 85

Enter the second number: 15

The greatest common divisor of 85 and 15 is 5.

Program analysis

Tip: if the number an is divisible by the number b, an is called a multiple of b, and b is called a divisor. The common divisor of several integers is called the common divisor of these numbers; the largest of them is called the greatest common divisor of these numbers.

The first to 12 lines of the program, for the realization of the program algorithm, encapsulate the algorithm into a function. Lines 14 and 15 prompt the user to input any two numbers, and finally line 16 outputs the operation result. When outputting, the user input num1 and num2 are used as parameters, and the result is returned to print to the function hcf,hcf, and the result is output.

Here we mainly analyze the core program hcf function: the second line def hcf (XMague y):, which is the fixed part of the function definition, and the argument is XMagine y.

Lines 5 to 8, find the smallest number in x and y, and assign the value to the variable smaller

Lines 9 to 11, through a loop, find 1 to smaller, divide the numbers of x and y at the same time, and assign the maximum number to hcf.

Line 12 returns the HCF value, the highest common divisor, to the program segment that called the function, where line 16 is returned, and the program ends at last.

After reading the above, do you have any further understanding of how to find the maximum common divisor in Python? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Tags: Maximum common divisor maximum common divisor function program input number result two content user output minimum number parameter algorithm divisor and will analysis prompt Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Microsoft MariaDB NVidia OPPO Reno