Computer >> Computer tutorials >  >> Programming >> Javascript

Validating a power JavaScript


We are required to write a JavaScript function that in a number, say n, as the only input. The function should then validate if the input number is a power of 3 or not.

If it is a power of 3, we should return true, false otherwise.

For example −

isPowerOf3(243) = true
isPowerOf3(343) = false
isPowerOf3(81) = true

Example

const num = 243;
var isPowerOf3 = (num = 3) => {
   let divisor = num === 1 ? 1 : 3; while(divisor < num){
      divisor *= 3;
   };
   return divisor === num;
};
console.log(isPowerOf3(num));
console.log(isPowerOf3(343));
console.log(isPowerOf3(81));

Output

And the output in the console will be −

true
false
true