计算最大公因数

PythonPythonBeginner
立即练习

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

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

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


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ModulesandPackagesGroup -.-> python/using_packages("Using Packages") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") python/PythonStandardLibraryGroup -.-> python/math_random("Math and Random") subgraph Lab Skills python/comments -.-> lab-13646{{"计算最大公因数"}} python/lists -.-> lab-13646{{"计算最大公因数"}} python/tuples -.-> lab-13646{{"计算最大公因数"}} python/function_definition -.-> lab-13646{{"计算最大公因数"}} python/importing_modules -.-> lab-13646{{"计算最大公因数"}} python/using_packages -.-> lab-13646{{"计算最大公因数"}} python/standard_libraries -.-> lab-13646{{"计算最大公因数"}} python/math_random -.-> lab-13646{{"计算最大公因数"}} end

最大公因数

编写一个名为 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() 来计算一组数字的最大公因数。