Project Euler Problem 48 Solution

The series, 1^(1) + 2^(2) + 3^(3) + ... + 10^(10) = 10405071317.

Find the last ten digits of the series, 1^(1) + 2^(2) + 3^(3) + ... + 1000^(1000).

My solution in Ruby:

sum = 0
for i in 1..1000 do
  sum += i**i
end
str = sum.to_s
 
puts str[str.length - 10,str.length]

UPDATE

s = 0
(1..1000).inject { |s, x| s + x ** x } % (10 ** 10)
str = s.to_s
puts str[str.length - 10,str.length]

2 Comments

  1. Paul Jones
    Apr 10, 2009 @ 16:22:58

    A shorter solution would be:
    (1..1000).inject { |s, x| s + x ** x } % (10 ** 10)

    (http://snippets.dzone.com/posts/show/2161 has some good details on the inject method)

    Reply

  2. Paul Jones
    Apr 10, 2009 @ 23:33:34

    The % (10 ** 10) takes the last 10 digits – so the entire string selection part is un-needed too!

    Reply

Leave a Reply