最大公約数の計算

Beginner

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

はじめに

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