本文实例讲述了Python基于递归和非递归算法求两个数最大公约数、最小公倍数。分享给大家供大家参考,具体如下:
最大公约数和最小公倍数的概念大家都很熟悉了,在这里就不多说了,今天这个是因为做题的时候遇到了所以就写下来作为记录,也希望帮到别人,下面是代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
#!/usr/bin/env python
#coding:utf-8
from fractions import gcd
#非递归实现
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!!!'
#递归实现
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自带的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 )
|
结果如下:
12
4
6
Number is wrong!!!
None
----------------------------------------------------------------------------
12
4
2
----------------------------------------------------------------------------
12
4
希望本文所述对大家Python程序设计有所帮助。
原文链接:https://blog.csdn.net/together_cz/article/details/69708092