DEV Community

Riches
Riches

Posted on

Playing with digits "Codewars"

Some numbers have funny properties. For example:

89 --> 8¹ + 9² = 89 * 1

695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2

46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p

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.
In other words:

Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k

If it is the case we will return k, if not return -1.

Note: n and p will always be given as strictly positive integers.

Steps.

  1. Lets Convert n which is a number to an Array and to to that we have to convert to a string first.
  2. Let create a variable total which will hold the sum of all numbers in the array.
  3. lets create our loop which will iterate over the array we created in step 1
  4. inside the array we are going to raise each number to the power of p then add it to the variable total we created in step 2
  5. we will increase our p by 1 because the power goes in an increasing order.
  6. now we need to find a number which when multiplied with n will give us total. the best way to do that is to divide total by n.
  7. now lets do our comparison. if the dividend is an integer we will return it, else we return -1 which means no number was found.

Solution.

function digPow(n, p){
    let nArr = n.toString().split("")
    let total = 0
    for (let index = 0; index < nArr.length; index++) {
        const element = nArr[index];
        total += Math.pow(parseInt(element), p)
        p++
    }
    let compare = total / n
    if(Number.isInteger(compare)){
        return compare
    }else{
        return -1
    }
}
console.log(digPow(46288, 3));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)