名词解释:
LCM(least common multiple):最小公倍数
HCF(highest common factor)or GCD(greatest common divisor):最大公约数
算法:
1.暴力法
较大数除以2个数没有余数即得到结果,如果不是,则使最大数自增知道找到结果
'''
function computeLcm:
input: x y
output: lcm
'''
def computeLcm(x,y):
if (x > y):
greater = x
else:
greater = y
while(True):
if((greater%x == 0) & (greater%y == 0)):
lcm = greater
break
greater += 1
return lcm
这种算法最简单,但相对地运行速度比较慢。
基于一个公式
我们通过以下实现这个方法(相同点在于gcd过程使用辗转相除法,区别在于求gcd的过程是否使用递归)
2.递归方法
递归的核心是调用自身
'''
function RecursiveGcd:
input: x y
output: gcd
recursive
'''
def RecursiveGcd(x,y):
if y == 0:
return x
else:
return RecursiveGcd(y, x%y)
'''
function computeLcmWithRecursiveGcd:
input: x y
output: lcm
'''
def computeLcmWithRecursiveGcd(x,y):
lcm = (x*y)//RecursiveGcd(x,y)
return lcm
3.非递归方法
'''
function NonRecursiveGcd:
input: x y
output: gcd
non-recursive
'''
def NonRecursiveGcd(x,y):
while(y):
x , y = y , x % y
return x
'''
function computeLcmWithNonRecursiveGcd:
input: x y
output: lcm
'''
def computeLcmWithNonRecursiveGcd(x,y):
lcm = (x*y)//NonRecursiveGcd(x,y)
return lcm
分析:无论是递归法还是非递归法,本质都是使用辗转相除法来求得最大公约数,然后通过两数相乘处以最大公约数来球的最小公倍数。
分析:递归调用实际上是函数自己在调用自己,而函数的调用开销是很大的,系统要为每次函数调用分配存储空间,并将调用点压栈予以记录。而在函数调用结束后,还要释放空间,弹栈恢复断点。所以说,函数调用不仅浪费空间,还浪费时间。
部分库的方法:fractions库(主要用于分数运算相关)中的gcd方法,我们用ctrl+左键查看函数实现
发现也是非递归实现
几种方法时间消耗测试结果:
从以上的运行结果大致可以证明,效率:非递归方法 > 递归方法 > 暴力方法
以下附上全部代码:
#coding:utf-8
'''
Created on 2018年9月21日
@author: love_paeonia
'''
import time
from fractions import gcd
'''
function computeLcm:
input: x y
output: lcm
'''
def computeLcm(x,y):
if (x > y):
greater = x
else:
greater = y
while(True):
if((greater%x == 0) & (greater%y == 0)):
lcm = greater
break
greater += 1
return lcm
'''
function RecursiveGcd:
input: x y
output: gcd
recursive
'''
def RecursiveGcd(x,y):
if y == 0:
return x
else:
return RecursiveGcd(y, x%y)
'''
function computeLcmWithRecursiveGcd:
input: x y
output: lcm
'''
def computeLcmWithRecursiveGcd(x,y):
lcm = (x*y)//RecursiveGcd(x,y)
return lcm
'''
function NonRecursiveGcd:
input: x y
output: gcd
non-recursive
'''
def NonRecursiveGcd(x,y):
while(y):
x , y = y , x % y
return x
'''
function computeLcmWithNonRecursiveGcd:
input: x y
output: lcm
'''
def computeLcmWithNonRecursiveGcd(x,y):
lcm = (x*y)//NonRecursiveGcd(x,y)
return lcm
if __name__ == '__main__':
start1 = time.clock()
computeLcm(7, 131)
print "function computeLcm time cost: " + (time.clock() - start1).__str__()
start2 = time.clock()
computeLcmWithRecursiveGcd(7, 131)
print "function computeLcmWithRecursiveGcd time cost: " + (time.clock() - start2).__str__()
start3 = time.clock()
computeLcmWithNonRecursiveGcd(7, 131)
print "function computeLcmWithNonRecursiveGcd time cost: " + (time.clock() - start3).__str__()
start4 = time.clock()
gcd(7, 131)
print "function fractions.gcd time cost: " + (time.clock() - start4).__str__()