How to Implement the Least Common Multiple in a Ruby Program
In this lesson, we are going to solve problem #5 in Project Euler using some insanely simple Ruby code. The problem asks us to solve: What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

In this guide we are going to solve a math problem asks us:

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Ruby really shines when it comes to answering questions like these. In fact the entire solution to this problem is below:

p (1...20).to_a.reduce(:lcm)

In this code we are converting a range of numbers from 1 to 20 to an array. On this array, we are calling the reduce method and passing the built-in lcm method. The lcm method will get the least common multiple of the value passed to it.

If you execute this code, the answer is 232792560. Which is the right solution!

This code illustrates the power of functional methods and how it can make coding a much easier and more enjoyable experience in Ruby.