I use the following function to calculate log base 2 for integers:
public static int log2(int n){
if(n <= 0) throw new IllegalArgumentException();
return 31 - Integer.numberOfLeadingZeros(n);
}
Does it have optimal performance?
Does someone know ready J2SE API function for that purpose?
UPD1 Surprisingly for me, float point arithmetics appears to be faster than integer arithmetics.
UPD2 Due to comments I will conduct more detailed investigation.
UPD3 My integer arithmetic function is 10 times faster than Math.log(n)/Math.log(2).