|
| 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 | +``` |
0 commit comments