Created
May 22, 2013 03:57
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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