Skip to content

Commit ecaee0d

Browse files
committed
feat: add power sum digits solution
1 parent 238f876 commit ecaee0d

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

codewars/power-sum-digits/README.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Numbers that are a power of their sum of digits
2+
3+
## Description
4+
5+
The number 81 has a special property, a certain power of the sum of its digits is equal to 81 (nine squared). Eighty one (81), is the first number in having this property (not considering numbers of one digit). The next one, is 512. Let's see both cases with the details
6+
7+
8 + 1 = 9 and 92 = 81
8+
9+
512 = 5 + 1 + 2 = 8 and 83 = 512
10+
11+
We need to make a function that receives a number as argument n and returns the n-th term of this sequence of numbers.
12+
13+
**Examples (input --> output)**
14+
15+
```txt
16+
1 --> 81
17+
18+
2 --> 512
19+
```
20+
21+
Happy coding!

codewars/power-sum-digits/solution.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
function powerSumDigTerm(n) {
2+
const arr = [];
3+
for (let i = 2; i < 100; i++) {
4+
for (let j = 2; j < 10; j++) {
5+
const num = i ** j;
6+
const sum = num
7+
.toString()
8+
.split('')
9+
.reduce((a, b) => Number(a) + Number(b), 0);
10+
if (sum === i) arr.push(num);
11+
}
12+
}
13+
return arr.sort((a, b) => a - b)[n - 1];
14+
}
15+
16+
module.exports = powerSumDigTerm;
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
const powerSumDigTerm = require('./solution');
2+
3+
describe('Numbers that are a power of their sum of digits', () => {
4+
const testCases = [
5+
{
6+
input: 1,
7+
output: 81,
8+
},
9+
{
10+
input: 2,
11+
output: 512,
12+
},
13+
{
14+
input: 3,
15+
output: 2401,
16+
},
17+
{
18+
input: 4,
19+
output: 4913,
20+
},
21+
{
22+
input: 5,
23+
output: 5832,
24+
},
25+
];
26+
27+
it('should return a number type', () => {
28+
expect(typeof powerSumDigTerm(1)).toBe('number');
29+
});
30+
31+
it.each(testCases)('should return $output', (testCase) => {
32+
expect(powerSumDigTerm(testCase.input)).toBe(testCase.output);
33+
});
34+
});

0 commit comments

Comments
 (0)