Checking if a number is a valid power of 4 in JavaScript


Problem

We are required to write a JavaScript function that takes in a single integer, num, as the only argument. Our function should check whether this number is a valid power of 4 or not. If it is a power of 4, we should return true, false otherwise.

For example, if the input to the function is −

const num1 = 2356;
const num2 = 16;

Then the output should be −

const output1 = false;
const output2 = true;

Example

The code for this will be −

const num1 = 2356;
const num2 = 16;
const isPowerOfFour = (num = 1) => {
   let bool = false;
   for(let i = 0; i < 16; i++){
      if( Math.pow(4,i) === num){
         bool=true;
         return bool;
      };
   };
   return bool;
};
console.log(isPowerOfFour(num1));
console.log(isPowerOfFour(num2));

Output

And the output in the console will be −

false
true

Updated on: 19-Mar-2021

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements