Greatest common divisors in Python

The greatest common divisor (GCD) is the largest positive number that divides all numbers in a given list. Python's math.gcd() function makes it easy to find the GCD of multiple numbers by applying it iteratively.

Problem Statement

Given a list of positive numbers, find the largest positive number that divides each number in the list.

For example, if the input is [14, 28, 70, 56], the output should be 14 since 14 divides all these numbers.

Algorithm

To solve this problem, we follow these steps ?

  • Initialize result with the first element of the list
  • For each subsequent number in the list:
    • Calculate GCD of current result and the number
    • Update result with this GCD
  • Return the final result

Implementation

import math

class Solution:
    def solve(self, nums):
        ans = nums[0]
        for x in nums:
            ans = math.gcd(ans, x)
        return ans

# Test the solution
ob = Solution()
result = ob.solve([14, 28, 70, 56])
print(f"GCD of [14, 28, 70, 56] is: {result}")
GCD of [14, 28, 70, 56] is: 14

How It Works

The algorithm leverages the mathematical property that gcd(a, b, c) = gcd(gcd(a, b), c). Starting with the first number, we iteratively compute the GCD with each subsequent number.

Step-by-step Example

import math

nums = [14, 28, 70, 56]
ans = nums[0]  # ans = 14

print(f"Initial: ans = {ans}")

for i, x in enumerate(nums[1:], 1):
    old_ans = ans
    ans = math.gcd(ans, x)
    print(f"Step {i}: gcd({old_ans}, {x}) = {ans}")

print(f"Final GCD: {ans}")
Initial: ans = 14
Step 1: gcd(14, 28) = 14
Step 2: gcd(14, 70) = 14
Step 3: gcd(14, 56) = 14
Final GCD: 14

Alternative Approach Using reduce()

Python's functools.reduce() provides a more concise solution ?

import math
from functools import reduce

def find_gcd(nums):
    return reduce(math.gcd, nums)

# Test with the same example
numbers = [14, 28, 70, 56]
result = find_gcd(numbers)
print(f"GCD using reduce: {result}")

# Test with different numbers
numbers2 = [48, 18, 24]
result2 = find_gcd(numbers2)
print(f"GCD of [48, 18, 24]: {result2}")
GCD using reduce: 14
GCD of [48, 18, 24]: 6

Conclusion

Finding the GCD of multiple numbers involves iteratively applying math.gcd() to pairs of numbers. Both the loop-based approach and functools.reduce() method are effective, with reduce() offering more concise code for this mathematical operation.

---
Updated on: 2026-03-25T10:23:04+05:30

333 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements