等我学完数论我就来填坑!!
说到最大公因(gcd)),我们就不得不提辗转相除法,本身也是一种递归的方式,假设求a和b的最大公因数,那么基本步骤为:
r = a % b
a = b
b = r
直到余数为0(b=0)时,此时的a就是a和b的最大公因数
代码为:
def gcb(a, b): if b == 0: return a else: return gcb(b, a % b) if __name__ == "__main__": a = 4 b = 5 print(gcb(a, b))
如果是判断一个列表的最大公因数,那我们在构造最大公因数之后,可以再构造一个递归的函数,基本的思想为:只要得出第[n-1]数和前面n-2个数的最大公因数就可以了
def gcb(a, b): if b == 0: return a else: return gcb(b, a % b) def gcd_nums(nums): n = len(nums) if not nums: return 0 if n == 1: return nums[0] else: return gcb(nums[n - 1], gcd_nums(nums[:n - 1])) if __name__ == "__main__": numbers = [11, 66, 88, -99, 0] print(gcd_nums(numbers))
在最大公因数的基础上,我们可以得到最小公倍数(lcm),有一个公式:
lcm = (a * b) / gcd(a, b)
def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) def gcd_nums(nums): n = len(nums) if not nums: return -1 if n == 1: return nums[0] else: return gcd(nums[n - 1], gcd_nums(nums[:n - 1])) # 递归的求解一组数的最大公倍数 def lcm_nums(nums): n = len(nums) if not nums: return -1 if n == 1: return nums[0] else: return lcm(nums[n - 1], lcm_nums(nums[:n - 1])) def lcm(a, b): return (a * b) // gcd(a, b) if __name__ == "__main__": numbers = [11, 66, 88, -99, 0] print(gcd_nums(numbers)) print(lcm_nums(numbers))