Skip to content

Instantly share code, notes, and snippets.

@nimamehanian
Created May 22, 2013 03:57
Show Gist options
  • Save nimamehanian/5625140 to your computer and use it in GitHub Desktop.
Save nimamehanian/5625140 to your computer and use it in GitHub Desktop.
Find the largest palindrome (of number_of_digits length) that is also a perfect square. E.g., largest_pal_perf_sq(15) returns 900_075_181_570_009
def palindrome?(text)
return true if text.length <= 1
return false if text[0] != text[text.length - 1]
return palindrome?(text[1..-2])
end
def prepare_range(number_of_digits)
big = ''
sml = '1'
number_of_digits.times do
big << '9'
sml << '0'
end
# Remove extra zero
sml.chop!
return [sml, big]
end
def largest_pal_perf_sq(number_of_digits)
range = prepare_range(number_of_digits)
lower_range = Math.sqrt(range[0].to_i).ceil
upper_range = Math.sqrt(range[1].to_i).floor
upper_range.downto(lower_range) do |sqrt|
number_in_question = sqrt * sqrt
return number_in_question if palindrome?(number_in_question.to_s)
end
return false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment