A Ruby Solution to Project Euler Problem 16

April 28, 2020

Project Euler if you didn’t know is an online site dedicated to mathematical problems, a lot of these can be solved using a naive solution, but the real beauty comes from solving them using clever algorithms.

I’ve been learning Ruby recently so I thought I’d have a go at some of the problems, learning a language using problem sites such as project euler is a great way to do it as you’re forced to learn the key features such as arrays, hashes etc.

Problem 16 says:

2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 21000?

And using Ruby these can just be a one-liner! Imagine solving this in C, it would be at-least 50 lines.

puts (2**1000).to_s.chars.map(&:to_i).sum

And on my machine it solves it almost instantly. Great.

I’ve really been enjoying Ruby because there is also one clear way to do something, unlike C++ where there are about 10,000.

Back to top