Implementing the least common multiple
In this section, we are going to solve a math problem that asks: what is the smallest positive number that is evenly divisible by all the numbers from 1 to 20?
Ruby really shines when it comes to answering questions such as these. In fact, the entire solution to this problem is shown as follows:
p (1...20).to_a.reduce(:lcm)
In this code, we converted a range of numbers from 1 to 20 into an array. On this array, we called the reduce
method and passed 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 will be 232792560
, which is the right solution.
This code illustrates the power of functional methods and how they can make coding a much easier and more enjoyable experience in Ruby.