Mathematics for Programmers - GCD using Euclid's algorithm
Video credits : mycodeshool
In this tutorial you'll learn to calculate GCD using Euclid's algorithm.
The Euclidean algorithm is based on the principle that the greatest common divisor of two numbers does not change if the larger number is replaced by its difference with the smaller number. For example, 21 is the GCD of 252 and 105 (as 252 = 21 × 12 and 105 = 21 × 5), and the same number 21 is also the GCD of 105 and 252 − 105 = 147. Since this replacement reduces the larger of the two numbers, repeating this process gives successively smaller pairs of numbers until the two numbers become equal. When that occurs, they are the GCD of the original two numbers.
//assume that a and b cannot both be 0
public int GCD(int a, int b)
{
if (b==0) return a;
return GCD(b,a%b);
}
No problems available for this topic.
Join the community of 1 Lakh+ Developers
Create a free account and get access to tutorials, jobs, hackathons, developer events and neatly written articles.
Create a free account