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

Factorial Digit Sum

\(n!\) means \(n \times (n - 1) \times … \times 3 \times 2 \times 1\).

For example, \(10! = 10\times 9 \times … \times 3 \times 2 \times 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!\).

Solution

Thanks to Scala’s extensive standard library, we can represent the factorial in question as a regular BigInt. It even has a convenient .factorial method.

Once we have the result of \(100!\), we can recursively read it, digit by digit, using the modulo division.

import EulerHelper.*

import scala.annotation.tailrec

object Euler020 extends EulerApp {
  override def execute(): Any = {
    sumDigits(BigInt(100).factorial)
  }

  @tailrec
  private def sumDigits(n: BigInt, result: BigInt = 0): BigInt =
    if (n == 0) result
    else sumDigits(n / 10, result + n % 10)
}