Find whether a given number is a power of 4 or not in C++


In this problem, we are given an integer N. Our task is to find whether a given integer is a power of 4 or not.

Let's take an example to understand the problem,

Input : N = 64
Output : Yes

Explanation

43 = 64

Solution Approach

A simple solution to the problem is by recursively dividing the number by 4 and checking whether the resultant number is divided by 4 or not. If the value after recursive division becomes 1, return true.

Example

Program to illustrate the working of our solution

#include <iostream>
using namespace std;
bool isPowerOf4(int n){
   if(n == 0)
   return 0;
   while(n != 1)
   {
      if(n % 4 != 0)
         return 0;
      n = n / 4;
   }
   return 1;
}
int main(){
   int n = 123454;
   if (isPowerOf4(n))
      cout<<"The number is a power of 4";
   else
      cout<<"The number is not a power of 4";
   return 0;
}

Output

The number is not a power of 4

Updated on: 01-Feb-2022

489 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements