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

I have provided a straight-forward, brute force solution to the problem below. Though the question talks about ordering the terms numerically, there’s no reason to do so. The only thing you need be concerned with is the number of distinct terms. If I were solving this problem in C#, I might leverage the C# HashSet to gather the terms. But I’m still focused on Ruby and it didn’t take long to hunt down the Ruby Set class.

As always, any feedback is welcome.

# Euler 29
# http://projecteuler.net/index.php?section=problems&id=29
# Consider all integer combinations of ab for 2 <= a <= 5
# and 2 <= b <= 5:
#
# 2^2=4, 2^3=8, 2^4=16, 2^5=32
# 3^2=9, 3^3=27, 3^4=81, 3^5=243
# 4^2=16, 4^3=64, 4^4=256, 4^5=1024
# 5^2=25, 5^3=125, 5^4=625, 5^5=3125
#
# If they are then placed in numerical order, with any
# repeats removed, we get the following sequence of 15
# distinct terms:
#
# 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
#
# How many distinct terms are in the sequence generated by ab
# for 2 <= a <= 100 and 2 <= b <= 100?
timer_start = Time.now

require 'set'
distinct_terms = Set.new

(2..100).each do |a|
  (2..100).each do |b|
    distinct_terms << a**b
  end
end

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

4 Comments to “Project Euler 29: Ruby”

  1. I think this is among the most vital info for me. And i am glad reading your article. But should remark on some general things, The web site style is wonderful, the articles is really excellent : D. Good job, cheers

  2. Really nice design and excellent subject material, absolutely nothing else we require :D .

  3. Rattling nice design and superb content material , practically nothing else we want : D.

  4. I like the valuable info you provide in your articles. I¡¯ll bookmark your blog and check again here regularly. I am quite sure I¡¯ll learn lots of new stuff right here! Good luck for the next!

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>