Project Euler in Ruby: Problem 20

  • by

Switching to Ruby for a quick one-liner of Project Euler.

Problem 20:

Factorial Digit Sum

n! means n × (n − 1) × … × 3 × 2 × 1

For example, 10! = 10 × 9 × … × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Find the sum of the digits in the number 100!

I was able to reuse most the code from my Problem 16 solution, I just needed to calculate the factorial at the beginning of it (no built-in factorial function in Ruby).


answer = (1..100).inject(:*).to_s.split('').map(&:to_i).reduce(:+)

puts answer

--output: 648

Questions or comments? Feel free to leave them below or reach out to me on Twitter!

https://theoldreader.com/profile/BigDaddyK

Leave a Reply

Your email address will not be published. Required fields are marked *