最大公約数の計算

PythonPythonBeginner
今すぐ練習

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

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

数学において、2つ以上の整数の最大公約数(GCD:Greatest Common Divisor)は、各整数を割り切って余りのない最大の正の整数です。たとえば、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() を使って数値のリストの最大公約数を計算する方法を学びました。