Greatest common divisor in Python

Problem

Given two integers A less than B. Write Python code to find the greatest common divisor between A and B commonly known as GCD.

Definition

GCD(A, B) is the largest positive integer that divides A and B without a remainder. We can loop starting at 2 ending at A and whenever we find a divisor for both A and B we update our result. At the end of the loop we will have GCD already computed.

Solution

Here is a sample Python code to do that

Euclidean algorithm

We can use the Euclidean algorithm to solve this problem efficiently. The Euclidean algorithm is based on the fact that the GCD of two numbers does not change if the smaller number is subtracted from the larger number. Here is an example:

Code

Here is an iterative implementation in Python

Here is the recursive Python version of the Euclidean algorithm

If you have questions or comments, please use the comments section below. Thanks for reading.

Add a Comment

Your email address will not be published. Required fields are marked *