Project Euler Problem 48 Solution

Question

The series, 11+22+33+...+1010=104050713171^1 + 2^2 + 3^3 + ... + 10^{10} = 10405071317.

Find the last ten digits of the series, 11+22+33+...+100010001^1 + 2^2 + 3^3 + ... + 1000^{1000}.

Clojure

#!/usr/bin/env clojure
(defn raise [x n]
  (. (. java.math.BigInteger (valueOf x)) (pow n)))

(defn raise-to-itself [number]
  (raise number number))

(defn digits [n]
  (map #(- (int %) 48) (str n)))

(def result (reduce + (map raise-to-itself (range 1 1001))))
(println (apply str (reverse (take 10 (reverse (digits result))))))
$ time clojure raise-to-itself.clj
real   0m0.742s
user   0m1.324s
sys    0m0.036s

Haskell

lastN :: Int -> [a] -> [a]
lastN n xs = foldl (const . drop 1) xs (drop n xs)

main :: IO ()
main = putStrLn $ lastN 10 $ show $ sum [x^x | x <- [1..1000]]
$ ghc -O2 -o self-powers self-powers.hs
$ time ./self-powers
real   0m0.005s
user   0m0.004s
sys    0m0.000s

Ruby

#!/usr/bin/env ruby
puts (1..1000).reduce(0) { |s,n| s + n**n }.to_s[-10..-1]
$ time ruby power-series.rb
real   0m0.036s
user   0m0.032s
sys    0m0.000s

Questions? Comments? Send me an email: [email protected]