Project Euler - Problem 20: Factorial digit sum

2017/05/02


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!


When working with BIG numbers, R is (often) not that good. options(digits) allows only the maximum of 22 digits.

factorial(100)
## [1] 9.332622e+157
as.character(factorial(100))
## [1] "9.33262154439422e+157"

Even bit64 integer can’t handle BIG numbers.

bit64::as.integer64(factorial(100))
## Warning in as.integer64.double(factorial(100)): NAs produced by integer64
## overflow
## integer64
## [1] <NA>

Fortunately, package gmp provides an object of class bigz that handles large numbers pretty well.

result <- gmp::factorialZ(100)
result <- as.character(result)
result <- strsplit(result, "")
result <- as.integer(unlist(result))
result
##   [1] 9 3 3 2 6 2 1 5 4 4 3 9 4 4 1 5 2 6 8 1 6 9 9 2 3 8 8 5 6 2 6 6 7 0 0
##  [36] 4 9 0 7 1 5 9 6 8 2 6 4 3 8 1 6 2 1 4 6 8 5 9 2 9 6 3 8 9 5 2 1 7 5 9
##  [71] 9 9 9 3 2 2 9 9 1 5 6 0 8 9 4 1 4 6 3 9 7 6 1 5 6 5 1 8 2 8 6 2 5 3 6
## [106] 9 7 9 2 0 8 2 7 2 2 3 7 5 8 2 5 1 1 8 5 2 1 0 9 1 6 8 6 4 0 0 0 0 0 0
## [141] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Reduce(sum, result)
## [1] 648