Kaprekar number is a non-negative integer, the representation of whose square can be split into two parts that add up to the original number.
Write a function that determines if a given number is a Kaprekar number or not.
def kaprekar?(k)
result = false
power = k ** 2
power_str = power.to_s
for i in 0..(power_str.size - 1)
num1 = power_str[0,i].to_i
num2 = power_str[i,power_str.size-1].to_i
if k == num1 + num2
result = true
break
end
end
result
end
puts "Is kaprekar 9: #{kaprekar?(9)}"
puts "Is kaprekar 45: #{kaprekar?(45)}"
puts "Is kaprekar 7777: #{kaprekar?(7777)}"
puts "Is kaprekar -9: #{kaprekar?(-9)}"
puts "Is kaprekar 33: #{kaprekar?(33)}"
source 'https://rubygems.org'
gem 'rspec'
Gemfile
bundle install
Execute command:
.
├── Gemfile
├── Gemfile.lock
├── lib
│ └── kaprekar.rb
└── spec
Setup your directory structure to look like this:
require "kaprekar"
describe 'Kaprekar' do
it 'should return true when the input is 9 because 9 * 9 is 81 and 8 + 1 is 9' do
expect(kaprekar?(9)).to eq(true)
end
it 'should return false when the input is 8 because 8 * 8 is 64 and 6 + 4 is not 8' do
expect(kaprekar?(8)).to eq(false)
end
it 'should return false when the input is a negative integer' do
expect(kaprekar?(-9)).to eq(false)
end
end
spec/kaprekar_spec.rb
rspec -fd
Run:
Remember the points in our questions earlier?
require "kaprekar"
describe 'Kaprekar' do
it 'should return true when the input is 9 because 9 * 9 is 81 and 8 + 1 is 9' do
expect(kaprekar?(9)).to eq(true)
end
it 'should return false when the input is 8 because 8 * 8 is 64 and 6 + 4 is not 8' do
expect(kaprekar?(8)).to eq(false)
end
it 'should return false when the input is a negative integer' do
expect(kaprekar?(-9)).to eq(false)
end
end
easily understandable description
example input
expected output
- Ron Jeffries, founders of Extreme Programming
Throughout the day, we are going to teach you how to write clean code that works while discovering why it matters.
Failure to comply with non-negotiable etiquette will result in rm -rf to your code.
As a fan of geometry,
I want to model a line based on points consisting of (x, y) co-ordinates using the cartesian system,
So that I can calculate its length.
As a fan of geometry,
I want to compare two lines for equality based on the end points,
So that I know when two lines are the equal.
As a fan of geometry,
I want to model a rectangle with sides of lengths a and b,
So that I can calculate its perimeter.
- Robert C. Martin, author of Clean Code