-3
    public class test{
    public static void main(String[] args) {
    int a=536870912;
    System.out.print((Math.log(a)/Math.log(2)));
}
}

536870912 is a number that is power of two, but the result is 29.000000000000004, could anybody explain this? Thanks.

candlejack
  • 1,189
  • 2
  • 22
  • 51

3 Answers3

3

If n is a power of 2, then its binary representation will start with 1 and will contain only 0s after it.

So, you can do:

String binary = Integer.toBinaryString(a);
Pattern powerOfTwoPattern = Pattern.compile("10*");
System.out.println(powerOfTwoPattern.matcher(binary).matches());

Anyway, if you number is not really huge (i.e. fits the int or long range), then you can follow the suggestions here

Community
  • 1
  • 1
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0

You can use below method:-

boolean isPowerOfTwo (int x)
 {
  while (((x % 2) == 0) && x > 1) /* While x is even and > 1 */
   x /= 2;
  return (x == 1);
 }

Explanation:- Repeatedly divides x by 2. It divides until either the quotient becomes 1, in which case x is a power of two, or the quotient becomes odd before reaching 1, in which case x is not a power of two.

Amit Bhati
  • 5,569
  • 1
  • 24
  • 45
0

pseudo-code following, easily adapted to java

boolean is_power_of_two(int num)
{
    int i = Math.ceil(Math.log(num)/Math.log(2.0));
    /*while ( i >= 0 )
    {
        // note 1 is taken as power of 2, i.e 2 ^ 0
        // chnage i > 0 above to avoid this
        if ( num == (1 << i) ) return true;
        i--;
    }
    return false;*/
    // or even this, since i is initialised in maximum power of two that num can have
    return (num == (1 << i)) || (num == (1 << (i-1)));
}

NOTE it also can be done with discrete logarithm in constant-time without compiling to string represenation etc, but needs a precomputed table of discrete logarithms for base 2 or even using binary manipulation as in https://stackoverflow.com/a/600306/3591273, these approaches are constant-time but use the default representation of machine int or long

Community
  • 1
  • 1
Nikos M.
  • 8,033
  • 4
  • 36
  • 43