Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Power Digit Sum

\(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 \(2^{1000}\)?

Solution

Due to the rich standard library in Scala, this problem is extremely easy. We can solve it in one line only!

object Euler016 extends EulerApp {
  override def execute(): Int = (BigInt(2) ^ 1000).toString().map(_.asDigit).sum
}

It even runs very fast. If we wanted to avoid using BigInt, then it wouldn’t be much harder. We could store the individual digits in an array and each multiplication would double all the indexes by two. We’d also need to handle the carrying over.

Still pretty straightforward, not really worth the effort to go through it.