Skip to content

Instantly share code, notes, and snippets.

@flanger001
Created May 27, 2015 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flanger001/07f825aa4299e2cdf466 to your computer and use it in GitHub Desktop.
Save flanger001/07f825aa4299e2cdf466 to your computer and use it in GitHub Desktop.
Kaprekar number
# 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