![]() |
VOOZH | about |
The Greatest Common Divisor (GCD) of two numbers is the largest number that divides both numbers exactly without leaving a remainder. It is widely used in mathematics, cryptography, fractions, and competitive programming.
Find the GCD of 12 and 18
Factors of 12 -> 1, 2, 3, 4, 6, 12
Factors of 18 -> 1, 2, 3, 6, 9, 18
Common Factors -> 1, 2, 3, 6
Greatest Common Divisor (GCD) = 6
6
Explanation: The idea is to find the common divisor by checking the divisibility of both numbers using the (%) modulo operator with all the numbers starting from the minimum number to 1.
Below are some other ways to calculating GCD in C++:
The Euclidean algorithm is an efficient method to find the GCD of two numbers. It works on the principle that the GCD of two numbers remains the same if the greater number is replaced by the difference between the two numbers.
4
In C++ Standard Library, there are two standard library functions:__gcd() and gcd()which is used for calculating the GCD of two numbers but they are present since C++ 14 and C++ 17 standard only. __gcd()is defined inside <algorithm> header file and gcd() is defined inside <numeric> header file.
__gcd(a, b) // Since C++ 14
gcd(a, b) // Since C++ 17
Parameters
Return Value: return an "int" (gcd of both numbers).
4 4