Checking if a number is some power of the other JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in two numbers, let’s say m and n. The function should check whether m is some power of n or not.

If it is, then we should return true, false otherwise.

For example −

m = 8, n = 2 should return true
m = 100, n = 10 should return true
m = .01, n = 10 should return true
m = 21, n = 3 should return false

Example

const isPower = (m, n) => {
   let sign = m < 1;
   if (!m) {
      return false;
   };
   while (m !== 1) {
      if (sign) {
         m *= n;
      }
      else {
         m /= n;
      }
      if (sign ? m > 1 : m < 1) {
         return false;
      }
   };
   return true;
}
console.log(isPower(0.01, 10));
console.log(isPower(1000, 10));
console.log(isPower(1001, 10));
console.log(isPower(8, 2));
console.log(isPower(0.125, 2));

Output

This will produce the following output −

true
true
false
true
true
raja
Published on 25-Nov-2020 09:59:22
Advertisements