I'm doing the following program with the following instruction: Write a Java program to check whether a given integer is a power of 4 or not.
My approach is to take a log of the given number on base 4, and if we get an integer then the number is the power of 4.
Until now I haven't found a way to check if my calculation is an integer? Can you help me with that? Or maybe give me better tips about it?
I just used the dirty principle of :
if (x == (int)x) { ... }
But it seems to not work with my code.
Here is my code :
try (Scanner input = new Scanner(System.in)) { System.out.print("Enter number : "); int n = input.nextInt(); // get user input // System.out.println(Math.log(n) / Math.log(4)); // this is the calculation of log(n) base 4 if ((Math.log(n) / Math.log(4)) == (int) Math.log(n) / Math.log(4)) { // code never reach this part? System.out.println(input.nextInt() + " is a power of 4."); } else System.out.println(input.nextInt() + " is not a power of 4."); }