In my attempt to learn Ruby out in the open, here’s my solution for Project Euler Problem 50

And this is Euler Problem 50. I did it — I met my goal of completely the first 50 Euler Problems in Ruby by tomorrow, August 18. This was a fun problem which I did entirely on paper, in the living room, while the rest of the family watched TV. Oh how I wish that solution “just worked” but I neglected to move the counter to 1 and establish the new sum in the outer loop. Luckily, it didn’t take long to resolve, but, again, how I wish my solution to Problem 50 “just worked” the first time.

Is there any new Ruby goodness going on here? Nope, but I was reminded of my very first Ruby error which took a while to debug the first time around:

in `+’: nil can’t be coerced into Fixnum (TypeError)

If you notice below that (s+1) evaluates to an integer which allows the upto() loop to work its magic. Remove those parenthesis and you have a completely different expression — one which throws the above error. I don’t know. I figured I’d mention it, mostly because it offered me a nice reminder of how far I’ve come.

As always, any feedback is welcome.

# Euler 50
# http://projecteuler.net/index.php?section=problems&id=50
# The prime 41, can be written as the sum of six
# consecutive primes:
#
# 41 = 2 + 3 + 5 + 7 + 11 + 13
# This is the longest sum of consecutive primes that adds
# to a prime below one-hundred.
#
# The longest sum of consecutive primes below one-thousand
# that adds to a prime, contains 21 terms, and is equal to 953.
#
# Which prime, below one-million, can be written as the sum
# of the most consecutive primes?
timer_start = Time.now

require 'mathn'

top = 1_000_000

p = []
Prime.each do |a|
  break if a > top
  p << a
end

max_consecutive = 0
upper = p.length - 1
sum, ctr, answer = 0, 0, 0

0.upto(upper) do |s|
  sum, ctr = p[s], 1

  (s+1).upto(upper) do |e|
    sum += p[e]
    break if sum > top

    ctr += 1
    next if ctr < max_consecutive

    if sum.prime? && ctr > max_consecutive
      max_consecutive, answer = ctr, sum
    end
  end
end

puts max_consecutive
puts answer
puts "Elapsed Time: #{(Time.now - timer_start)*1000} milliseconds"

2 Comments to “Project Euler 50: Ruby”

  1. jon bristow says:

    no commentary, but congrats on level two!

  2. Ben Griswold says:

    Thanks Jon. And thanks for your encouragement along the way. I know you’ve completed well over 50 problems at this point, but look out because I’m on your heels. :)

Leave a Reply

You can wrap your code with [ruby][/ruby] or [python][/python] blocks for syntax highlighting and you can use these traditional tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>