3.4 KiB
3.4 KiB
id | title | challengeType |
---|---|---|
5a23c84252665b21eecc7eca | Kaprekar numbers | 5 |
Description
- It is 1, or,
- The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number.
2223
is a Kaprekar number, as2223 * 2223 = 4941729
,4941729
may be split to494
and1729
, and494 + 1729 = 2223
- The series of Kaprekar numbers is known as A006886, and begins as
1, 9, 45, 55, ...
Instructions
Tests
tests:
- text: <code>isKaprekar</code> should be a function.
testString: assert(typeof isKaprekar == 'function', '<code>isKaprekar</code> should be a function.');
- text: <code>isKaprekar(1, 10)</code> should return a boolean.
testString: assert(typeof isKaprekar(1, 10) == 'boolean', '<code>isKaprekar(1, 10)</code> should return a boolean.');
- text: <code>isKaprekar(1, 10)</code> should return <code>true</code>.
testString: assert.equal(isKaprekar(1, 10), true, '<code>isKaprekar(1, 10)</code> should return <code>true</code>.');
- text: <code>isKaprekar(9, 10)</code> should return <code>true</code>.
testString: assert.equal(isKaprekar(9, 10), true, '<code>isKaprekar(9, 10)</code> should return <code>true</code>.');
- text: <code>isKaprekar(2223, 10)</code> should return <code>true</code>.
testString: assert.equal(isKaprekar(2223, 10), true, '<code>isKaprekar(2223, 10)</code> should return <code>true</code>.');
- text: <code>isKaprekar(22823, 10)</code> should return <code>false</code>.
testString: assert.equal(isKaprekar(22823, 10), false, '<code>isKaprekar(22823, 10)</code> should return <code>false</code>.');
- text: <code>isKaprekar(9, 17)</code> should return <code>false</code>.
testString: assert.equal(isKaprekar(9, 17), false, '<code>isKaprekar(9, 17)</code> should return <code>false</code>.');
- text: <code>isKaprekar(225, 17)</code> should return <code>true</code>.
testString: assert.equal(isKaprekar(225, 17), true, '<code>isKaprekar(225, 17)</code> should return <code>true</code>.');
- text: <code>isKaprekar(999, 17)</code> should return <code>false</code>.
testString: assert.equal(isKaprekar(999, 17), false, '<code>isKaprekar(999, 17)</code> should return <code>false</code>.');
Challenge Seed
function isKaprekar(n, bs) {
// Good luck!
}
Solution
function isKaprekar(n, bs) {
if (n < 1) return false;
if (n == 1) return true;
for (var a = n * n, b = 0, s = 1; a; s *= bs) {
b += a % bs * s;
a = Math.floor(a / bs);
if (b && a + b == n) return true;
} return false;
}