For working professionals
For fresh graduates
More
The gcd (Greatest Common Divisor) of two numbers is the largest positive integer that divides both numbers without leaving a remainder. Calculating the gcd is a common task in mathematics and computer science, especially when working with fractions, cryptography, and optimization problems.
When working with Python, you can easily calculate the gcd of two numbers in Python using function or gcd of two numbers in Python using recursion. While both methods are effective, understanding the underlying approach can help you choose the best option for your specific use case.
In this guide, we’ll break down the process of calculating the gcd of two numbers step by step. You will learn how to implement the gcd calculation without using built-in functions and explore how recursion can simplify the process.
By the end, you'll be able to apply this concept to various real-world problems.
“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”
In Python, you can easily calculate the GCD of two numbers using built-in functions from the math module, which is part of Python's Standard Library (STL).
The gcd() function from this module is optimized for performance and reduces the need to write your own logic to find the greatest common divisor.
Let’s go through an example:
# Import the gcd function from the math module
import math
# Define two numbers
num1 = 56
num2 = 98
# Use the gcd function from the math module
gcd_value = math.gcd(num1, num2)
# Output the result
print(f"The GCD of {num1} and {num2} is: {gcd_value}")
Output:
The GCD of 56 and 98 is: 14
Explanation:
The first line imports the gcd function from Python’s math module, which is part of Python’s Standard Library. This function is pre-built to find the greatest common divisor.
We define two numbers, num1 = 56 and num2 = 98, for which we need to find the GCD.
The math.gcd() function is called with the two numbers as arguments. This function returns the greatest common divisor of the two numbers.
Finally, we print the result in a formatted string to show the gcd of the two numbers.
Why Use STL for GCD Calculation?
Also Read: Libraries in Python Explained: List of Important Libraries
“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”
Recursion works by breaking down the problem into smaller instances of itself. For calculating the GCD, we use the well-known Euclidean algorithm, which repeatedly finds the remainder of the division between two numbers until the remainder is 0. The divisor at that point will be the GCD.
Let’s walk through an example step by step to understand how to calculate the gcd of two numbers in Python using recursion.
# Recursive function to find the GCD of two numbers
def gcd_recursive(a, b):
# Base case: If the second number is zero, return the first number as the GCD
if b == 0:
return a
# Recursive call: Pass the second number and the remainder of a divided by b
else:
return gcd_recursive(b, a % b)
# Define two numbers
num1 = 56
num2 = 98
# Call the gcd_recursive function
gcd_value = gcd_recursive(num1, num2)
# Output the result
print(f"The GCD of {num1} and {num2} is: {gcd_value}")
Output:
The GCD of 56 and 98 is: 14
Explanation:
The first step is to check if the second number (b) is 0. If b is zero, the function returns a, as the GCD of any number and 0 is the number itself. This is the stopping condition for the recursion.
If b is not zero, the function calls itself with two arguments: b (the second number) and the remainder of the division of a by b (a % b). The remainder operation keeps reducing the numbers until b becomes zero.
The function keeps calling itself until b becomes 0, at which point the last non-zero divisor will be the GCD. In our case, 56 and 98 have a GCD of 14.
Why Use Recursion for GCD Calculation?
In Python, you can easily implement the GCD calculation using the Euclidean algorithm, and it’s a great example to demonstrate the power of both iteration and recursion in finding the greatest common divisor.
# Function to calculate GCD using Euclidean Algorithm
def euclidean_algorithm(a, b):
# While loop continues until the second number becomes zero
while b != 0:
# The remainder is found and assigned to 'b'
a, b = b, a % b
# When 'b' is 0, 'a' holds the GCD
return a
# Define two numbers
num1 = 56
num2 = 98
# Call the Euclidean algorithm function
gcd_value = euclidean_algorithm(num1, num2)
# Output the result
print(f"The GCD of {num1} and {num2} using Euclidean Algorithm is: {gcd_value}")
Output:
The GCD of 56 and 98 using Euclidean Algorithm is: 14
Explanation:
The Euclidean algorithm starts by dividing the larger number by the smaller number and storing the remainder. It then replaces the larger number with the smaller number and the smaller number with the remainder. This process continues until the remainder is zero.
The loop will keep iterating until b (the smaller number) becomes 0. In each iteration, a and b are updated: a takes the value of b, and b is assigned the remainder of a % b.
When b reaches zero, the current value of a will be the GCD. In this case, the GCD of 56 and 98 is 14.
Why Use the Euclidean Algorithm for GCD?
In Python, you can also calculate the GCD of two numbers in Python using function by utilizing a lambda function. A lambda function is a small anonymous function that can be defined in a single line.
This approach offers a concise way to define simple functions, such as calculating the GCD of two numbers.
Let’s walk through an example:
# Define a lambda function to calculate GCD using the Euclidean algorithm
gcd_lambda = lambda a, b: a if b == 0 else gcd_lambda(b, a % b)
# Define two numbers
num1 = 56
num2 = 98
# Call the lambda function to find the GCD
gcd_value = gcd_lambda(num1, num2)
# Output the result
print(f"The GCD of {num1} and {num2} using lambda function is: {gcd_value}")
Output:
The GCD of 56 and 98 using lambda function is: 14
Explanation:
A lambda function is defined using lambda a, b:. This is followed by an expression that checks if b is 0. If b is 0, it returns a as the GCD. If b is not 0, it calls the lambda function recursively with b and the remainder of a % b.
The lambda function calls itself with updated values (b and a % b). The recursion continues until b becomes zero, at which point the current value of a will be the GCD.
The final output shows that the GCD of 56 and 98 is 14, just like the other methods we explored, but this time achieved with a lambda function.
Why Use Lambda Functions for GCD Calculation?
In Python, the Binary GCD algorithm, also known as Stein's Algorithm, efficiently calculates the GCD of two numbers. This method uses binary operations (bitwise shifts) instead of division and modulus, making it computationally faster, especially for large numbers.
Let’s explore this method with an example:
# Function to calculate GCD using Binary GCD Algorithm (Stein's Algorithm)
def binary_gcd(a, b):
# Base case: If one of the numbers is zero, return the other number
if a == 0:
return b
if b == 0:
return a
# If both numbers are even, divide both by 2
if a % 2 == 0 and b % 2 == 0:
return 2 * binary_gcd(a // 2, b // 2)
# If one number is even and the other is odd, divide the even number by 2
if a % 2 == 0:
return binary_gcd(a // 2, b)
if b % 2 == 0:
return binary_gcd(a, b // 2)
# If both numbers are odd, subtract the smaller from the larger and recurse
if a > b:
return binary_gcd((a - b) // 2, b)
else:
return binary_gcd(a, (b - a) // 2)
# Define two numbers
num1 = 56
num2 = 98
# Call the binary_gcd function
gcd_value = binary_gcd(num1, num2)
# Output the result
print(f"The GCD of {num1} and {num2} using Binary GCD Algorithm is: {gcd_value}")
Output:
The GCD of 56 and 98 using Binary GCD Algorithm is: 14
Explanation:
If either number is zero, return the other number as the GCD (this is the stopping condition for the recursion).
If both numbers are even, divide them by 2 and multiply the result by 2, as the GCD of even numbers will also be even.
If one number is even and the other is odd, divide the even number by 2 and continue the process.
If both numbers are odd, subtract the smaller number from the larger and recurse with the new values, divided by 2 to minimize the difference.
Why Use the Binary GCD Algorithm (Stein's Algorithm)?
In Python, you can calculate the GCD using a linear search approach, also known as the "Linear Quest" method.
This method checks each number, starting from 1 and moving up to the smaller of the two numbers, identifying the largest number that divides both without leaving a remainder.
Let’s look at an example:
# Function to calculate GCD using Linear Quest
def linear_quest_gcd(a, b):
# Start from the smallest number and check for divisibility
smallest = min(a, b)
for i in range(smallest, 0, -1):
# Check if i divides both numbers
if a % i == 0 and b % i == 0:
return i # Return the largest divisor (GCD)
# Define two numbers
num1 = 56
num2 = 98
# Call the linear quest function
gcd_value = linear_quest_gcd(num1, num2)
# Output the result
print(f"The GCD of {num1} and {num2} using Linear Quest is: {gcd_value}")
Output:
The GCD of 56 and 98 using Linear Quest is: 14
Explanation:
This method starts at the smallest of the two numbers and checks for divisibility. It iterates through all the numbers from the smallest number down to 1, checking if both numbers are divisible by the current number in the loop.
The loop runs from the smallest of the two numbers down to 1. For each iteration, it checks whether both numbers are divisible by the current number (without leaving a remainder).
The function returns the largest number that divides both numbers. In this case, for numbers 56 and 98, the largest divisor is 14, so the GCD is 14.
Why Use the Linear Quest for GCD?
The linear quest approach is straightforward, but it is less efficient than other methods, such as the Euclidean algorithm. It requires checking every number up to the smaller of the two input values, making it slower for large numbers. However, it can still be useful for educational purposes or when working with smaller numbers.
The gcd of two numbers in python using function refers to calculating the greatest common divisor using a Python function, which can be done using recursion or built-in functions.
You can use recursion to calculate the GCD by repeatedly applying the Euclidean algorithm, where the function calls itself until one number becomes zero.
Yes, using the Euclidean algorithm for the gcd of two numbers in python using function is efficient, as it quickly reduces the size of the numbers involved.
Absolutely! Recursion is a natural fit for the gcd of two numbers in python using function, as it allows the problem to be broken down into smaller, more manageable sub-problems.
The gcd of two numbers in python using function is useful in cryptography, number theory, and optimization problems, where finding common divisors is often needed.
The gcd of two numbers in python using recursion involves a recursive function that calculates the greatest common divisor by applying the Euclidean algorithm. It’s a simple and effective approach.
Optimization can be done by using Python's built-in math.gcd() function, which is highly optimized, or by refining your recursive algorithm to reduce the number of calls.
Yes, you can calculate the gcd of two numbers in Python using iterative functions, such as loops or Python's built-in functions like math.gcd().
The best method depends on your needs. Recursion provides a clean solution, while Python’s math.gcd() is highly efficient for large numbers.
Yes, the gcd of two numbers in python using recursion can be applied to negative numbers, as the algorithm works with absolute values of the numbers.
The main advantages are simplicity and efficiency, especially when combined with recursion or Python's built-in methods, making it easy to find the gcd quickly.
Ready to challenge yourself? Take our Free Python Quiz!
Pavan Vadapalli
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.