本文實(shí)例講述了Python基于遞歸和非遞歸算法求兩個(gè)數(shù)最大公約數(shù)、最小公倍數(shù)。分享給大家供大家參考,具體如下:
最大公約數(shù)和最小公倍數(shù)的概念大家都很熟悉了,在這里就不多說了,今天這個(gè)是因?yàn)樽鲱}的時(shí)候遇到了所以就寫下來作為記錄,也希望幫到別人,下面是代碼:
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 #非遞歸實(shí)現(xiàn) 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!!!' #遞歸實(shí)現(xiàn) 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 ) |
結(jié)果如下:
12
4
6
Number is wrong!!!
None
----------------------------------------------------------------------------
12
4
2
----------------------------------------------------------------------------
12
4
希望本文所述對大家Python程序設(shè)計(jì)有所幫助。
原文鏈接:https://blog.csdn.net/together_cz/article/details/69708092