Greatest common factor calculator

Greatest common factor problem

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

What is a greatest common factor

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.

How to find the greatest common factor

Here is a sample C++ code to do that

Solution

The first solution is inefficient in case of large numbers. There is a very efficient approach to solving this problem known as the Euclidean algorithm. 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. Since the larger number is reduced repeating the same step produces smaller numbers until one of them is zero. In that case the GCD is the remaining nonzero number. To illustrate that look at the following example:

Code

Here is an iterative implementation in C++

Here is the recursive flavor 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 *