Projekt Euler – probem 4 in Ruby
Contact me at LinkedIn  RailsZilla at Facebook  RailsZilla at twitter   google +1  Contact me at Xing  connect me at github

Projekt Euler – probem 4 in Ruby

Posted in Ruby

Let’s go on with part four of our mathematical soultions-series in Project Euler:

Problem: The Largest palindrome product

A palindromic number reads the same both ways.
The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.

We first need a palindrome method. Let’s define it like this:

1
2
3
4
5
6
7
def palindrome? x
  # convert into String
  y = x.to_s
  # define look as the length of "y" divided by 2
  look = y.length / 2
  y[0..(look-1)] == y[-look..-1].reverse
end

We now need a method if it is divideable.

1
2
3
4
5
6
def divideable? x
  # because 999 ist the biggest number with three digits,
  # we count it down to the smallest which is 100
  999.downto(100).each { |y| return true if x % y == 0 && (x / y).to_s.length == 3 }
  false
end

Now we can piece together our puzzle:

1
2
3
4
5
6
7
8
9
10
# we count down from the largest six digit number which could be possible
# as a result of two three digit numbers multiplied
999999.downto(100000).each do |y|
  # now use the palindrome method and our divided method as condition
  if palindrome?(y) && divideable?(y)
    # print the result out
    puts "The result is #{y}"
    break
  end
end

This was easy to understand and hopefully gave you an inspiration how to deal with mathematical problems in Ruby.
Have a great day

Tags: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Please enter a secure code to see if you are a spammer ;-)

 

Copyright © 2011-2017  - RailsZilla – Ruby on Rails tutorials, tips and tricks All rights reserved. | Imprint | Privacy