Python Greatest Common Divisor Algorithm
The following code implements the greatest common divisor algorithm:
Example (Python 3.0+)
Filename : test.py
author by : www.runoob.com
Defining a function
def
hcf
(
x
,
y
)
:
"""
This function returns the greatest common divisor of two numbers
"""
Get the smaller 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
The user enters two numbers
num1
=
int
(
input
(
"
Enter the first number:
"
)
)
num2
=
int
(
input
(
"
Enter the second number:
"
)
)
(
num1
,
"
and
"
,
num2
,
"
the greatest common divisor of
"
,
hcf
(
num1
,
num2
)
)
The output of the code above is:
输入第一个数字: 54
输入第二个数字: 24
54 和 24 的最大公约数为 6
Python3 Examples