Calculating Greatest Common Divisor

PythonPythonBeginner
Practice Now

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

Introduction

In mathematics, the greatest common divisor (GCD) of two or more integers, is the largest positive integer that divides each of the integers without a remainder. For example, the GCD of 8 and 12 is 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{{"`Calculating Greatest Common Divisor`"}} python/lists -.-> lab-13646{{"`Calculating Greatest Common Divisor`"}} python/tuples -.-> lab-13646{{"`Calculating Greatest Common Divisor`"}} python/function_definition -.-> lab-13646{{"`Calculating Greatest Common Divisor`"}} python/importing_modules -.-> lab-13646{{"`Calculating Greatest Common Divisor`"}} python/using_packages -.-> lab-13646{{"`Calculating Greatest Common Divisor`"}} python/standard_libraries -.-> lab-13646{{"`Calculating Greatest Common Divisor`"}} python/math_random -.-> lab-13646{{"`Calculating Greatest Common Divisor`"}} end

Greatest Common Divisor

Write a function called gcd(numbers) that takes a list of integers as an argument and returns their greatest common divisor. Your function should use functools.reduce() and math.gcd() over the given list.

from functools import reduce
from math import gcd as _gcd

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

Summary

In this challenge, you have learned how to calculate the greatest common divisor of a list of numbers using functools.reduce() and math.gcd().

Other Python Tutorials you may like