Given a positive number, check if it is a power of four or not.

Practice this problem

Approach 1

A simple solution is to calculate log4n for a given number n. If it returns an integral value, then we can say that the number is a power of four.

This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

256 is a power of 4

Java


Download  Run Code

Output:

256 is a power of 4

Python


Download  Run Code

Output:

256 is a power of 4

Approach 2

The given number n is a power of 4 if it is a power of 2 and its only set bit is present at even position (0, 2, 4, …).

How to check for power of 2?

The expression n & (n-1) will unset the rightmost set bit of a number. If the number is a power of 2, it has only a 1–bit set, and n & (n-1) will unset the only set bit. So, we can say that n & (n-1) returns 0 if n is a power of 2; otherwise, it’s not a power of 2.

We can also the expression (n & -n) == n to check if a positive integer is a power of 2 or not. For more details, refer to this post.

How to check position of the set bit?

To check the position of its set bit, we can use 0xAAAAAAAA as a mask. The mask 0xAAAAAAAA has 1 in all its odd position. So if the expression !(n & 0xAAAAAAAA) is true, the position of the set bit in n is even.

(0xAAAAAAAA)16 = (10101010101010101010101010101010)2

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

256 is a power of 4

Java


Download  Run Code

Output:

256 is a power of 4

Python


Download  Run Code

Output:

256 is a power of 4

Approach 3

The given number n is a power of 4 if it is a power of 2 and its remainder is 1 when it is divided by 3. This approach is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

256 is a power of 4

Java


Download  Run Code

Output:

256 is a power of 4

Python


Download  Run Code

Output:

256 is a power of 4

Exercise: Check if the number is a power of 8 or 16 or not

(Hint – Check the bit pattern. Use mask 0xB6DB6DB6 to check for power of 8 and 0xEEEEEEEE for power of 16)