×

Check whether a Number is a Power of 4 or Not in Java

There are many ways to figure out if an integer is a power of 4. This section will go over a variety of techniques for figuring out whether or not a number is a power of four.

Examples:

Input: n = 9

Result: 9 is not pow of 4

Input: n = 14

Result: 12 is not pow of 4.

Input: n = 16

Result: 16 is pow of 4. 4^2 = 16

Approach: Using log base 4 with ceil and floor

Using this method, we calculate the input number's log4 value. J is a number that is a power of 4 if the result of the log4(j), where j is the input number, is an integer; otherwise, it is not.

// java program

public class NPF   
{    
// a technique that determines whether or not y is a power of 4 public booleanisPOF(int j)   
{    


double db = (Math.log(j) / Math.log(4));    


booleanisPow = Math.ceil(db) == Math.floor(db);    


return isPow;    


}     


// main method   
public static void main(String argvs[])   
{   
 
// building a NumPowFour class object 
NPF ob = new NPF();    


int a2 = 17;   
if(ob.isPOF(a2))   
{   
System.out.println(a2 + " is pow of four. ");       
}   
else   
{   
System.out.println(a2 + " is not pow four. ");       
}     


a2 = 256;   
if(ob.isPOF(a2))   
{   
System.out.println(a2 + " is pow of four. ");       
}   
else   
{   
System.out.println(a2 + " is not pow four. ");       
}    


a2 = 8;   
if(ob.isPOF(a2))   
{   
System.out.println(a2 + " is pow of four. ");       
}   
else   
{   
System.out.println(a2 + " is not pow four. ");       
}    
a2 = 16;   if(ob.isPOF(a2))   
{   
System.out.println(a2 + " is pow of four. ");       
}   
else   
{   
System.out.println(a2 + " is not pow four. ");       
}
     
}   
} 

Output:

17 is not pow four.  
256 is pow of four.  
8 is not pow four.  
16 is pow of four

Checking for power of 2

The rightmost set bit of a number will be unset by the formula a& (a-1). a& (a-1) will unset the only set bit if the number is a power of 2, which only has one bit set. Therefore, we can state that a& (a-1) returns 0 if n is a power of 2 and returns nonzero otherwise.

To determine if a positive integer is a power of two or not, we may alternatively use the phrase (a& -a) == a.

Approach: Using log base 4 without ceil and floor

Using this method, we determine the log4 value of the input number (say, the input number is j). Assume that the value is t. As an exponent of the integer 4, or 4(int), we take an integral part of the value. When the value is j, j is a power of four; otherwise, it is not.

// java program

public class NPF1   
{    


// a technique that determines whether or not y is a power of 4 public booleanisPOF(int j)   
{    


return (j> 0 &&Math.pow(           
4, (int)(Math.log(j) / Math.log(4) )) == j);   
}     


// main method   
public static void main(String argvs[])   
{    


// building a NPF1 class object NPF1 ob = new NPF1();    


int a2 = 17;   
if(ob.isPOF(a2))   
{   
System.out.println(a2 + " is pow of four. ");       
}   
else   
{   
System.out.println(a2 + " is not pow four. ");       
}     


a2 = 256;   
if(ob.isPOF(a2))   
{   
System.out.println(a2 + " is pow of four. ");       
}   
else   
{   
System.out.println(a2 + " is not pow four. ");       
}    
a2 = 8;   
if(ob.isPOF(a2))   
{   
System.out.println(a2 + " is pow of four. ");       
}   
else   
{   
System.out.println(a2 + " is not pow four. ");       
}    


a2 = 16;   
if(ob.isPOF(a2))   
{   
System.out.println(a2 + " is pow of four. ");       
}   
else   
{   
System.out.println(a2 + " is not pow four. ");       
}     


}   
}  

Output:

17 is not pow four.  
256 is pow of four.  
8 is not pow four.  
16 is pow of four

Approach: Divide by 4

Step 1: determine whether the inputted integer is divisible by 4 or not. The input number is not a power of four if it is not divisible.

Step 2: Multiply the number by 4 if it is divisible. The input number is a power of 4 if the result of division is 1, which is the case. Repeat steps 1 and 2 if the obtained number is not 1.

Let's observe how it is put into practice.

public class NPF2   
{    


// a technique that determines whether or not y is a power of 4 public booleanisPOF(int j)   
{    
do   
{   
if(j == 1)   
{   
return true;   
}   
else if(j % 4 == 0)   
{   j = j / 4;       
}   else   
{   
return false;   
}    


}while(true);    


}     


// main method   
public static void main(String argvs[])   
{    


// building a NPF2 class object 
NPF2 ob = new NPF2(); 
   
int a2 = 17;   
if(ob.isPOF(a2))   
{   
System.out.println(a2 + " is pow of four. ");       
}   
else   
{   
System.out.println(a2 + " is not pow four. ");       
}     


a2 = 256;   if(ob.isPOF(a2))   
{   
System.out.println(a2 + " is pow of four. ");       
}   
else   
{   
System.out.println(a2 + " is not pow four. ");       
}    


a2 = 8;   if(ob.isPOF(a2))   
{   
System.out.println(a2 + " is pow of four. ");       
}  
 else   
{   
System.out.println(a2 + " is not pow four. ");       
}    


a2 = 16;   if(ob.isPOF(a2))   
{   
System.out.println(a2 + " is pow of four. ");       
}   
else   
{   
System.out.println(a2 + " is not pow four. ");       
}     


}   
} 

Output:

17 is not pow four.  
256 is pow of four.  
8 is not pow four.  
16 is pow of four

Approach: Set bit

Any number that is a power of two shares the property of having only one set bit in its binary form. Look at the table below.

Number Binary representation
1 1
2 10
3 11
4 100
5 101
6 110
7 111
8 1000
9 1001
10 1010

The numerals 1, 2, 4, and 8 have only one bit set. All of these numbers are powers of 2, with 20 being a 1, 21 being a 2, 22 being a 4, and 23 being an 8.

The properties of a number that is a power of four are as follows:

Since a power 4 number is always a power 2 number, there is only one bit set in that number.

It must be an even number of zeros after the set bit. In binary, 2 equals 10, and the number of zeros following the set bit is 1, which is strange. As a result, 2 is not a power of 4. The binary representation of 16 is 10000, and the even number of zeros following the set bit is 4, making a total of 16. 16 is therefore a power of four.

The software that follows will use the qualities listed above to determine the numbers that are powers of 4.

// java program

public class NPF3   
{    


// a procedure that determines whether or not j is a power of 4 
public booleanisPOF(int j)   
{    


// for checking only one bit is set or not   
if((j& (j - 1)) == 0)   
{     
  int countZ = 0;       
 // loop for count the zeros after the set bit       
while((j& 1) == 0)       
{  
 countZ = countZ + 1;            
// shifting the bit by 1;   
j = j>> 1;       
}         


// determining whether or if there are even or odd numbers of zeros after the set bit     
return (countZ % 2 == 0) ? true : false;   
}    


// reaching here indicates that there are several set bits, hence the number cannot be a power of 4. 
return false;    
}    


 // main method   
public static void main(String argvs[])   
{    


// building a NPF3 class object 
NPF3 ob = new NPF3();    
int a2 = 17;   
if(ob.isPOF(a2))   
{   
System.out.println(a2 + " is pow of four. ");       
}   
else   
{   
System.out.println(a2 + " is not pow four. ");       
}     


a2 = 256;   
if(ob.isPOF(a2))   
{   
System.out.println(a2 + " is pow of four. ");       
}  
 else   
{   
System.out.println(a2 + " is not pow four. ");       
}   


 a2 = 8;   
if(ob.isPOF(a2))   
{   
System.out.println(a2 + " is pow of four. ");       
}  
 else  
 {   
System.out.println(a2 + " is not pow four. ");       
}    


a2 = 16;   
if(ob.isPOF(a2))  
 {   
System.out.println(a2 + " is pow of four. ");       
}   
else   
{   
System.out.println(a2 + " is not pow four. ");       
} 
    
}   
}  

Output:

17 is not pow four.  
256 is pow of four.  
8 is not pow four.  
16 is pow of four

It is also possible to perform the & operation using 0xAAAAAAAA instead of counting zeros after the set bit. It's crucial to use the & operation with the value 0xAAAAAAAA because it eliminates any values with an odd number of zeros after the set bit (2, 8, 32, etc.). Take note of the program below.

// java program

public class NPF4 


{ 


// a procedure that determines whether or not j is a power of 4


public booleanisPOF(int j) 


{ 


// for checking only one bit is set or not 


if((j& (j - 1)) == 0) 


{ 


    // removing any powers of two that are not powers of four Example: 2, 8, 32, etc.


    return ((j& 0xAAAAAAAA) == 0) ? true : false; 


} 


// reaching here indicates that there are several set bits, hence the number cannot be a power of 4.


return false; 


} 


// main method 


public static void main(String argvs[]) 


{ 


// building a NPF4 class object


NPF4 ob = new NPF4(); 


int a2 = 17; 


if(ob.isPOF(a2)) 


{ 


System.out.println(a2 + " is pow of four. ");     
} 
else 
{ 
System.out.println(a2 + " is not pow four. ");     
} 


a2 = 256; 
if(ob.isPOF(a2)) 
{ 
System.out.println(a2 + " is pow of four. ");     
} 
else
{ 
System.out.println(a2 + " is not pow four. ");     
} 
a2 = 8; 


if(ob.isPOF(a2)) 


{ 


System.out.println(a2 + " is pow of four. ");     


} 


else 


{ 


System.out.println(a2 + " is not pow four. ");     


} 


a2 = 16; 


if(ob.isPOF(a2)) 


{ 


System.out.println(a2 + " is pow of four. ");     


} 


else 


{ 


System.out.println(a2 + " is not pow four. ");     


} 


} 


}

Output:

17 is not pow four.  
256 is pow of four.  
8 is not pow four.  
16 is pow of four

Approach: Perfect Square

Any integer that is a power of 4, since 4 is a perfect square, must also be a perfect square. The two factors listed below are sufficient to determine whether a number is a power of four or not.

The quantity must be a power of two.

The quantity must be an exact square.

// java program

public class NPF5 


{ 


// a procedure to determine whether or not the integer j is a perfect square.


public booleaniPSqr(int j) 


{ 


    int ps = (int) Math.sqrt(j); 


    return ((ps * ps) == j); 


} 


// a procedure to determine whether or not the integer j is a perfect square.


public booleanisPOF(int j) 


{ 


int nu = 2; 


if(iPSqr(j)) 


{ 


// Check to see whether an integer is a power of two if it is a perfect square.


while(true) 


{ 


    if(nu == j) 


    { 


        return true; 


    } 


    else if ( nu >j) 


    { 


        return false; 


    } 


    nu = nu* 2;  


} 


} 


// reaching here indicates that the number is not a perfect square, hence it cannot be a power of four.


return false; 


} 


// main method 


public static void main(String argvs[]) 


{ 


// building a NPF5 class object


NPF5 obj = new NPF5(); 


int a2 = 17; 


if(ob.isPOF(a2)) 


{ 


System.out.println(a2 + " is pow of four. ");     


} 


else 


{ 


System.out.println(a2 + " is not pow four. ");     


} 


a2 = 256; 


if(ob.isPOF(a2)) 


{ 


System.out.println(a2 + " is pow of four. ");     


} 


else 


{ 


System.out.println(a2 + " is not pow four. ");     


} 


a2 = 8; 


if(ob.isPOF(a2)) 


{ 


System.out.println(a2 + " is pow of four. ");     


} 


else 


{ 


System.out.println(a2 + " is not pow four. ");     


} 


a2 = 16; 


if(ob.isPOF(a2)) 


{ 


System.out.println(a2 + " is pow of four. ");     


} 


else 


{ 


System.out.println(a2 + " is not pow four. ");     


} 


} 


}

Output:

17 is not pow four.  
256 is pow of four.  
8 is not pow four.  
16 is pow of four.

Related Topics

Collections in Java

Collection framework is one of Java's most powerful subsystems. It is a set of classes and interfaces that is all-the-rage technology for superintending objects and a group of objects. In...

6 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Lazy loading in Java

Lazy loading is the idea of waiting to load an object until you need it. In other words, it is the practice of postponing class instantiation until it is necessary....

5 minutes read.

Java Command Line Argument

Command-line arguments are passed to the main() method when we want to pass information into a program during runtime. It is the information that directly follows the program’s name on the...

1 minute read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

Davis Staircase Problem in Java

Davis has several stairs in his home and prefers to ascend one, two, or three steps at a time. As a highly clever youngster, he thinks about how many ways...

3 minutes read.

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

String Programs in Java

String Programs in Java: In Java, a String is an immutable object that represents a sequence of characters. For example, “Tutorial” is a string that consists of 8 characters: ‘T’,...

10 minutes read.

How to compare characters in Java

In this tutorial, we will learn about how to compare characters in Java. To compare characters in Java, we will learn about what is a character in Java Char The character is...

4 minutes read.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 minutes read.

Fibonacci Series Program in Java

Fibonacci Series Program in Java using Recursion Fibonacci series is a series whose every term is comprised of adding its previous two terms, barring the first two terms 0 and 1....

3 minutes read.

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes read.

Java vs Dot Net

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of...

5 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

Difference between Aggregation and Composition in Java

What is Aggregation? Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first...

8 minutes read.

Applet Program in Java

Applet Program in Java An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side....

3 minutes read.

Java delete directory

The File classes in Java may symbolize a directory or a file on the system. Inside the java.io package, the Files class is accessible. The File class has several helpful...

2 minutes read.

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.