How to Implement a Factorial Algorithm in Ruby
Another interesting problem that we are going to tackle in this lesson is problem #20 in Project Euler called the Factorial digit sum. In this program we need to solve the question: Find the sum of the digits in the number 100!. This is a perfect problem to practice a number of topics we have learned in this Ruby programming course.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

Another interesting problem that we are going to tackle is how to calculate the Factorial digit sum. In this program we need to solve the question:

Find the sum of the digits in the number 100!

This is a perfect problem to build a solution for because it combines a number of topics that we have learned in this Ruby programming course. I would even suggest for you to try building the program yourself before we head to the solution as this will give you a hands-on feel of Ruby algorithm development. You have all the knowledge needed to build it.

And if you get stuck, don't worry! We will still build it together.

If you're new to factorials, the question is self-explanatory. A factorial is a number that is the multiplied value of itself as well as all the digits up to 1. Factorials can get quite massive in a short period of time because they are a compounded multiple of a range of numbers. The sum of the individual digits of the factorial is the factorial digit sum. In this problem, we have to find the factorial digit sum of 100.

We are going to start by creating a method called factorial_value_sum_generator.

def factorial_value_sum_generator(factorial)
  arr = (1..factorial).to_a.reverse.each { |i| factorial += factorial * (i - 1)}
  factorial.to_s.split(//).map(&:to_i).inject(:+)
end

p factorial_value_sum_generator(100)

In this method we are sending the factorial as the argument. In the code we are creating an array and converting all the values from 1 to the factorial argument into an array. After that we are reversing this array because we want to multiply each value starting from the factorial argument value all the way to 1.

Next, we are going to iterate through the array with a variable i. Then, we are adding to the factorial the product of the factorial and the value after it. For example, if we have an array [10,9,8,7...1], then our code will multiply 10 with 9 *(that's the i-1), and the program will then add it to the factorial value, to give a total value of 19 during the first iteration.

Once that's done, we have to sum up the digits, and this is done in the next line by converting the factorial value into string and calling the split method on it. Next, we are calling the map method and passing the integer value as its argument. Finally, we are calling the inject method to add up all the values.

At the end, we print out the value returned by our method.

If you run the program, the output is 648, and that's right!