Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program for GCD of more than two (or array) numbers
In this article, we will learn how to find the Greatest Common Divisor (GCD) of more than two numbers or an array of numbers using Python.
Problem statement ? Given an array of numbers, we need to find the greatest common divisor of all elements.
The GCD of multiple numbers can be calculated by repeatedly finding the GCD of pairs of numbers. We start with the first two numbers, find their GCD, then find the GCD of that result with the third number, and so on.
Algorithm
The approach involves:
- Implement a function to find GCD of two numbers using Euclidean algorithm
- Apply this function iteratively to all numbers in the array
- GCD(a, b, c) = GCD(GCD(a, b), c)
Using Custom GCD Function
Here's how to implement GCD calculation from scratch ?
def findgcd(x, y):
while(y):
x, y = y, x % y
return x
numbers = [22, 44, 66, 88, 99]
result = numbers[0]
for i in range(1, len(numbers)):
result = findgcd(result, numbers[i])
print("GCD is:", result)
GCD is: 11
Using math.gcd() Function
Python's math module provides a built-in GCD function for cleaner code ?
import math
from functools import reduce
numbers = [22, 44, 66, 88, 99]
result = reduce(math.gcd, numbers)
print("GCD is:", result)
GCD is: 11
Step-by-Step Example
Let's trace through the algorithm to understand how it works ?
def findgcd(x, y):
while(y):
x, y = y, x % y
return x
numbers = [48, 18, 24]
print("Numbers:", numbers)
result = numbers[0]
print(f"Starting with: {result}")
for i in range(1, len(numbers)):
old_result = result
result = findgcd(result, numbers[i])
print(f"GCD({old_result}, {numbers[i]}) = {result}")
print(f"Final GCD: {result}")
Numbers: [48, 18, 24] Starting with: 48 GCD(48, 18) = 6 GCD(6, 24) = 6 Final GCD: 6
Comparison of Methods
| Method | Code Length | Performance | Best For |
|---|---|---|---|
| Custom Function | Longer | Good | Understanding algorithm |
| math.gcd() + reduce() | Shorter | Optimized | Production code |
Conclusion
Finding GCD of multiple numbers involves applying the two-number GCD algorithm iteratively. Use math.gcd() with reduce() for cleaner, more efficient code in real applications.
