Created
May 27, 2015 20:18
-
-
Save flanger001/07f825aa4299e2cdf466 to your computer and use it in GitHub Desktop.
Kaprekar number
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
# https://rubymonk.com/learning/books/1-ruby-primer/problems/150-kaprekar-s-number | |
def kaprekar?(k) | |
k_st = k.to_s | |
kk = k**2 | |
kk_st = kk.to_s | |
offset_length = kk.to_s.length.odd? ? k_st.length - 1 : k_st.length | |
left = kk_st[0, offset_length] | |
right = kk_st[offset_length, k_st.length] | |
k == left.to_i + right.to_i | |
end | |
numbers = [9, 46, 55, 90, 297, 703] | |
vals = [true, false, true, false, true, true] | |
vals == numbers.map { |n| kaprekar?(n) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment