How to Code the Power Digit Sum Algorithm in Ruby
In this lesson, we are going to see how to solve a complex math problem from Project Euler that asks us to solve the question: What is the sum of the digits of the number 2 to the 1000th power?
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 see how to solve a complex math problem that asks us to solve the question:

What is the sum of the digits of the number 2 to the 1000th power?

We can solve this problem with just one line of code in Ruby.

We're going to start by running the equation 2 to the 1000th and then converting the value to a string.

p (2 ** 1000).to_s

If you execute this code, the output is:

"10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376"

So this is the value of 2 to the power of 1000. The next part of the code should add each digit and create a final sum.

First, we want this string to be converted into an array of elements, and the code for this is will be:

p (2 ** 1000).to_s.split(//)

If you execute, the output will be the same as our string, except now each element will be its own element in an array.

Next, we have to convert everything to integer again so we can add them together, and we'll use the map method to do this.

p (2 ** 1000).to_s.split(//).map(&:to_i)

The output for this code will be the array:

[1, 0, 7, 1, 5, 0, 8, 6, 0, 7, 1, 8, 6, 2, 6, 7, 3, 2, 0, 9, 4, 8, 4, 2, 5, 0, 4, 9, 0, 6, 0, 0, 0, 1, 8, 1, 0, 5, 6, 1, 4, 0, 4, 8, 1, 1, 7, 0, 5, 5, 3, 3, 6, 0, 7, 4, 4, 3, 7, 5, 0, 3, 8, 8, 3, 7, 0, 3, 5, 1, 0, 5, 1, 1, 2, 4, 9, 3, 6, 1, 2, 2, 4, 9, 3, 1, 9, 8, 3, 7, 8, 8, 1, 5, 6, 9, 5, 8, 5, 8, 1, 2, 7, 5, 9, 4, 6, 7, 2, 9, 1, 7, 5, 5, 3, 1, 4, 6, 8, 2, 5, 1, 8, 7, 1, 4, 5, 2, 8, 5, 6, 9, 2, 3, 1, 4, 0, 4, 3, 5, 9, 8, 4, 5, 7, 7, 5, 7, 4, 6, 9, 8, 5, 7, 4, 8, 0, 3, 9, 3, 4, 5, 6, 7, 7, 7, 4, 8, 2, 4, 2, 3, 0, 9, 8, 5, 4, 2, 1, 0, 7, 4, 6, 0, 5, 0, 6, 2, 3, 7, 1, 1, 4, 1, 8, 7, 7, 9, 5, 4, 1, 8, 2, 1, 5, 3, 0, 4, 6, 4, 7, 4, 9, 8, 3, 5, 8, 1, 9, 4, 1, 2, 6, 7, 3, 9, 8, 7, 6, 7, 5, 5, 9, 1, 6, 5, 5, 4, 3, 9, 4, 6, 0, 7, 7, 0, 6, 2, 9, 1, 4, 5, 7, 1, 1, 9, 6, 4, 7, 7, 6, 8, 6, 5, 4, 2, 1, 6, 7, 6, 6, 0, 4, 2, 9, 8, 3, 1, 6, 5, 2, 6, 2, 4, 3, 8, 6, 8, 3, 7, 2, 0, 5, 6, 6, 8, 0, 6, 9, 3, 7, 6]

Lastly, we need to add the array elements together using the inject method.

p (2 ** 1000).to_s.split(//).map(&:to_i).inject(:+)

The final output is 1366.

So, we were able to solve a challenging problem with a single line of code by leveraging Ruby.