Skip to content

Commit 9abf229

Browse files
author
juanantonioledesma
committed
Add "Playing with digits" kata
1 parent 8bd1e2b commit 9abf229

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

6-kyu/playing-with-digits.md

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<h1>Playing with digits <sup><sup>6 Kyu</sup></sup></h1>
2+
3+
<sup>
4+
<a href="https://www.codewars.com/kata/5552101f47fc5178b1000050">
5+
<strong>LINK TO THE KATA</strong>
6+
</a> - <code>FUNDAMENTALS</code> <code>MATHEMATICS</code>
7+
</sup>
8+
9+
## Description
10+
11+
Some numbers have funny properties. For example:
12+
13+
> 89 --> 8¹ + 9² = 89 \* 1
14+
15+
> 695 --> 6² + 9³ + 5⁴= 1390 = 695 \* 2
16+
17+
> 46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 \* 51
18+
19+
Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p
20+
21+
- we want to find a positive integer k, if it exists, such that the sum of the digits of n taken to the successive powers of p is equal to k \* n.
22+
23+
In other words:
24+
25+
> Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n \* k
26+
27+
If it is the case we will return k, if not return -1.
28+
29+
**Note:** n and p will always be given as strictly positive integers.
30+
31+
```javascript
32+
digPow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1
33+
digPow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k
34+
digPow(695, 2) should return 2 since 6² + 9³ + 5= 1390 = 695 * 2
35+
digPow(46288, 3) should return 51 since 4³ + 6+ 2+ 8+ 8= 2360688 = 46288 * 51
36+
```
37+
38+
## Solution
39+
40+
```javascript
41+
const digPow = (n, p) => {
42+
const numbers = n
43+
.toString()
44+
.split('')
45+
.map(character => Number(character))
46+
47+
const powSum = numbers.reduce((acc, cur, i) => acc + Math.pow(cur, p + i), 0)
48+
49+
if (powSum === n * p) return p
50+
if (powSum % n === 0) return powSum / n
51+
return -1
52+
}
53+
```

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ JavaScript katas on Codewars are programming challenges that help you improve yo
5353
- **[Persistent Bugger](./6-kyu/persistent-bugger.md)**
5454
- **[Piano Kata, Part 1](./6-kyu/piano-kata-part-1.md)**
5555
- **[Piano Kata, Part 2](./6-kyu/piano-kata-part-2.md)**
56+
- **[Playing with digits](./6-kyu/playing-with-digits.md)**
5657
- **[Selective Array Reversing](./6-kyu/selective-array-reversing.md)**
5758
- **[Simple Fun #212: Processing Requests!](./6-kyu/simple-fun-212-processing-requests.md)**
5859
- **[Sort the odd](./6-kyu/sort-the-odd.md)**

0 commit comments

Comments
 (0)