Project Euler #48

I’ve been looking at the LazyList libraryhttp://flori.github.com/lazylist/doc/ for Ruby lately, and it’s helped with a couple of the Project Eulerhttp://projecteuler.net/ problems. I’d like a few more examples from them, but I’m starting to get the hang of using the library.

Here’s my solution for problem 48:

require 'lazylist'
list { n**n }.where( 
  :n => LazyList.from(1) 
).take( 1000 ).fold(0) { |sum,x| sum += x } % 10**10
  • An infinite list is produced, of all the natural numbers: LazyList.from(1)
  • Each of the natural numbers is raised to the power of itself to produce the series n²: list { n**n }
  • Take the first 1000 terms of the series: take( 1000 )
  • Fold them down into one term, the sum: fold(0) { |sum, x| sum += x }
  • Divide using modulus operator, by 10², which will only leave the remainder ,i.e. the last 10 digits.

There’s probably a more clever way to do it but I don’t know it, and I’m more interested in using the LazyList library to get used to it. It seems to be the closest thing to Haskell’s list comprehension syntax I’ve seen with Ruby, and is one of the things that makes Haskell so beautiful to look at (at times).

Added on:
Last updated: