Finding a number, when multiplied with input number yields input number in JavaScript


We are required to write a JavaScript function that takes in 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 as 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.


Following is the code −

 Live Demo

const num = 695;
const p = 2;
const findDesiredNumber = (num, p) => {
   let sum = 0;
   let str = String(num);
   for(const char in str){
      sum += str[char] * p;
   return Number.isInteger(sum/num) ? sum/num : -1;
console.log(findDesiredNumber(num, p));


Following is the console output −