Project Euler #48 in Ruby

Note: Don’t look at the code if you intend to solve the problem later.

Problem 48 – Project Euler

I was surprised at how easy this turned out to be. It is really, really simple because with Ruby, the only limit on how big an integer can get is how much memory you have available. Here’s my solution:

# Project Euler, 48
start = Time.now
 
n = 1
sum = 0
 
1000.times do
  sum += n**n
  n += 1
end
 
puts sum.to_s[-10..-1]
puts "Time taken: #{Time.now-start}"

It takes a fifth of a second on my laptop running Ruby 1.9.1.

Tags: , ,

2 Responses to “Project Euler #48 in Ruby”

  1. galactic says:

    its quite simple coding this problem in ruby…as i see from your code.But i have trying to solve the problem in c/c . And as these both languages do not permit max limit of an integer to exceed 10^11or 10^12 or so ,i m facing a bit problem…
    If possible i would like to ask you if you could tell the first 3 or four digits of your answer…

  2. Vikhyat Korrapati says:

    @galactic:

    I don’t think there is really any point in giving out the answer. If you really want to know, send me an email .

    I think the trick is probably to remove all the digits beyond the 10 you need before doing the exponent calculation. You’d probably want to write your own exponent function, something like this:

    function exp(num)
    {
      t = num
      num.times // do this num times
      {
        t = (last 10 digits of t) * (last 10 digits of num)
      }
      return t
    }
    

    That’s just pseudocode and I haven’t had an opportunity to test it yet, but I think that’s roughly how you do it.

Leave a Reply