The Ruby gcd()
function returns the GCD of two integers.
The GCD or Greatest Common Divisor of two numbers, i.e.,
num_1
andnum_2
, is the greatest positive number that divides both thenum_1
and thenum_2
.
Figure 1, below, shows the visual representation of the gcd()
function.
num_1.gcd(num_2)
# where num_1 and num_2 are the integers whose gcd is to be calculated
If
num_1
ornum_2
or both are non-integers, then this function throws anerror
.
This function requires another integer, (num_2)
, as a parameter.
This function returns the GCD of two integers.
The following example shows how to use the gcd()
function in Ruby.
#both positive numbersprint "(36).gcd(60) : ",(36).gcd(60) , "\n"#both negative numbersprint "(-24).gcd(-16) : ",(-24).gcd(-16) , "\n"#one of the numbers is zeroprint "(0).gcd(12) : ",(0).gcd(12), "\n"#one is negative and another is positiveprint "(-9).gcd(18) : ",(-9).gcd(18) , "\n"