What is lcm() in Ruby?

The Ruby lcm() function returns the LCM of two integers.

The LCM or least common multiple is the smallest number that is the multiple of all the numbers used to calculate LCM.

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

Figure 1: Visual representation of lcm() function

Syntax

num_1.lcm(num_2)
# where num_1 and num_2 are the integers whose lcm 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 LCM of two integers.

Code

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

# both positive numbers
print "(9).lcm(12) : ", (9).lcm(12), "\n"
# both negative numbers
print "(-24).lcm(-16) : ", (-24).lcm(-16), "\n"
# one of the numbers is zero
print "(0).lcm(12) : ", (0).lcm(12), "\n"
# one is negative and another is positive
print "(-9).lcm(18) : ", (-9).lcm(18), "\n"
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources