
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Whether a Given Number is a Power of 4 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
Advertisements