Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Greatest Common Divisor Algorithm

Python Greatest Common Divisor Algorithm

Document Object Reference Manual Python3 Examples

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:

"

)

)

print

(

num1

,

"

and

"

,

num2

,

"

the greatest common divisor of

"

,

hcf

(

num1

,

num2

)

)

The output of the code above is:


输入第一个数字: 54
输入第二个数字: 24
54 和 24 的最大公约数为 6

Document Object Reference Manual Python3 Examples