VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-whether-a-given-number-is-a-power-of-4-or-not/

⇱ Check for Power of 4 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check for Power of 4

Last Updated : 1 Apr, 2026

Given an integer n, find whether it is a power of 4 or not.

Example :

Input : n = 16
Output : true
Explanation: 16 is a power of 4

Input : 20
Output : false
Explanation: 20 is not a power of 4

Using Bit Manipulation - O(log n) Time and O(1) Space

The idea is to first check whether the number is a power of 2 (i.e., it has only one set bit), and then ensure that the position of this set bit is at an even index (counting from 0), which guarantees it is a power of 4. This can be verified using bit operations by confirming that n & (n - 1) == 0 and the set bit lies at an even position.


Output
True

Explanation: The binary representation of 64 is 1000000, which has only one set bit, so it is a power of 2. The position of this set bit (counting from 0) is 6, which is an even index. Since both conditions are satisfied, the number 64 is a power of 4.

Logarithmic Approach - O(1) Time and O(1) Space

If a number n is a power of 4, then log₄(n) will always be an integer. So, we compute log₄(n) and check whether its floor value is equal to its ceil value; if both are equal, it means the value is an integer and hence n is a power of 4.


Output
True

Explanation: For n = 64, we compute log base 4 of 64, which gives 3. Since this value is an integer, its floor and ceil values are equal. Hence, 64 is a power of 4.

Bit Masking Technique - O(1) Time and O(1) Space

The idea is to first check whether the number has only one set bit (i.e., it is a power of 2 using n & (n - 1) == 0). Then, we ensure that this set bit is not in any odd position by verifying that n & 0xAAAAAAAA == 0, since this mask has all bits set at odd positions. If both conditions are satisfied, the number is a power of 4.


Output
True

Note: A number can be identified as a power of 4 if it has only one set bit (i.e., it is a power of 2) and the number of trailing zeros is even. Using built-in functions like "__builtin_ctz(n)" in C++ or "Integer.numberOfTrailingZeros(n)" in Java, this condition can be checked efficiently in a single line.

Perfect Square + Modulo Approach - O(1) Time and O(1) Space

A number is a power of 4 if it is first a power of 2 (only one set bit), and additionally satisfies n % 3 == 1, since all powers of 4 leave a remainder of 1 when divided by 3.


Output
True

Explanation: First, we check whether 64 is a power of 2. The binary representation of 64 is 1000000, which has only one set bit, so it satisfies this condition. Next, we check the modulo condition: 64 % 3 = 1. Since both conditions are satisfied so 64 is a power of 4.

Comment
Article Tags: