Just finished Project 4.
This isn’t the most concice code, because i functionised it, but it works quite well.
class Numeric
def is_palindrome?
s_num = self.to_s
half = s_num[0..(s_num.length/2)-1].to_s
s_num == half + half.reverse or
(s_num.length%2 == 1 and s_num == half + s_num[s_num.length/2,1].to_s + half.reverse)
end
end
def find_largest_palindrome number_digits
highest_number = (9.to_s * number_digits).to_i
lowest_number = (1.to_s + 0.to_s* (number_digits - 1)).to_i
largest = 0
largest_sqrt = 0
highest_number.downto(lowest_number).each do |num1|
highest_number.downto(num1).each do |num2|
if largest_sqrt * 2 > num1 + num2
break
end
if (num1 * num2).is_palindrome? and num1 * num2 > largest
largest = num1 * num2
largest_sqrt = Math.sqrt(largest)
end
end
end
largest
end
puts "Largest palendrome is #{find_largest_palindrome 3}"