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

JavascriptWeb DevelopmentFront End Technology

Problem

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.

Example

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;
      p++;
   };
   return Number.isInteger(sum/num) ? sum/num : -1;
};
console.log(findDesiredNumber(num, p));

Output

Following is the console output −

-1
raja
Published on 19-Apr-2021 08:21:06
Advertisements