Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
math
gcd
communitycreator

What is gcd() in Ruby?

Harris Amjad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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"

RELATED TAGS

ruby
math
gcd
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring