Project Euler Problem 16 Solution

Question

215=327682^{15} = 32768 and the sum of its digits is 3+2+7+6+8=263 + 2 + 7 + 6 + 8 = 26.

What is the sum of the digits of the number 210002^{1000}?

Haskell

sumDigits ::  Integer -> Integer
sumDigits n = sumDigits' n 0
    where sumDigits' 0 acc = acc
          sumDigits' n acc = sumDigits' (div n 10) (acc + (mod n 10))

main ::  IO ()
main = print $ sumDigits $ 2^1000
$ ghc -O2 -o sumExp sumExp.hs
$ time ./sumExp
real   0m0.001s
user   0m0.000s
sys    0m0.000s

Python

#!/usr/bin/env python
print(sum(int(digit) for digit in str(2**1000)))
$ time python3 sum-exp.py
real   0m0.020s
user   0m0.016s
sys    0m0.000s

Ruby

#!/usr/bin/env ruby
puts (2**1000).to_s.each_char.inject(0) {|s,v| s+v.to_i}
$ time ruby sum-exp.rb
real   0m0.029s
user   0m0.020s
sys    0m0.008s

Questions? Comments? Send me an email: z@chdenton.com