计算最大公因数

Beginner

This tutorial is from open-source community. Access the source code

简介

在数学中,两个或多个整数的最大公因数(GCD)是能整除每个整数且无余数的最大正整数。例如,8 和 12 的最大公因数是 4。

最大公因数

编写一个名为 gcd(numbers) 的函数,它接受一个整数列表作为参数,并返回这些整数的最大公因数。你的函数应该对给定列表使用 functools.reduce()math.gcd()

from functools import reduce
from math import gcd as _gcd

def gcd(numbers):
  return reduce(_gcd, numbers)
gcd([8, 36, 28]) ## 4

总结

在这个挑战中,你已经学会了如何使用 functools.reduce()math.gcd() 来计算一组数字的最大公因数。