What is gcd() in Ruby?

The Ruby gcd() function returns the GCD of two integers.

The GCD or Greatest Common Divisor of two numbers, i.e., num_1 and num_2, is the greatest positive number that divides both the num_1 and the num_2.

Figure 1, below, shows the visual representation of the gcd() function.

Figure 1: Visual representation of gcd() function

Syntax

num_1.gcd(num_2)
# where num_1 and num_2 are the integers whose gcd is to be calculated

If num_1 or num_2 or both are non-integers, then this function throws an error.

Parameter

This function requires another integer, (num_2), as a parameter.

Return value

This function returns the GCD of two integers.

Code

The following example shows how to use the gcd() function in Ruby.

#both positive numbers
print "(36).gcd(60) : ",(36).gcd(60) , "\n"
#both negative numbers
print "(-24).gcd(-16) : ",(-24).gcd(-16) , "\n"
#one of the numbers is zero
print "(0).gcd(12) : ",(0).gcd(12), "\n"
#one is negative and another is positive
print "(-9).gcd(18) : ",(-9).gcd(18) , "\n"

Free Resources