GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them.
For example GCD of 20 and 28 is 4 and GCD of 98 and 56 is 14.
A simple solution is to find all prime factors of both numbers, then find intersection of all factors present in both numbers. Finally return product of elements in the intersection.
An efficient solution is to use Euclidean algorithm which is the main algorithm used for this purpose. The idea is, GCD of two numbers doesn’t change if smaller number is subtracted from a bigger number.
// C program to find GCD of two numbers
// Recursive function to return gcd of a and b
// Everything divides 0
(a == 0 || b == 0)
// base case
(a == b)
// a is greater
(a > b)
// Driver program to test above function
a = 98, b = 56;
"GCD of %d and %d is %d "
, a, b, gcd(a, b));
GCD of 98 and 56 is 14
Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits: http://www.geeksforgeeks.org
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at
http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements