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

I could be wrong, but I don’t see any exciting and new Ruby stuff going on here. The prime class continues to come in handy and I’m extending the integer class, but that’s about it.

As always, any feedback is welcome.

# Euler 46
# http://projecteuler.net/index.php?section=problems&id=46
# It was proposed by Christian Goldbach that every odd
# composite number can be written as the sum of a prime
# and twice a square.
#
# 9 = 7 + 212
# 15 = 7 + 222
# 21 = 3 + 232
# 25 = 7 + 232
# 27 = 19 + 222
# 33 = 31 + 212

# It turns out that the conjecture was false.
#
# What is the smallest odd composite that cannot be written
# as the sum of a prime and twice a square?
timer_start = Time.now

require 'mathn'

class Integer
  def composite?
    return !self.prime? && self != 1
  end

  def goldbach?
    # Loop through primes and numbers until
    # we exceed the value of self
    Prime.each do |p|
       return false if p >= self

       t, i = 1, 1
       while (t <= self)
        # prime + twice a square
        t = p + (2 * (i * i))

        return true if t == self
        i += 1
       end
    end

    false
  end
end

answer, i = 0, 1
while answer == 0
  answer = i if i.composite? && !i.goldbach?
  i+=2 # step 2 for odds
end

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

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>