/** This class includes static methods for calculating the logarithm (to ** base 2). ** ** @author R. McCloskey ** @version November 2006 */ public class Log2Calc { /** Calculates the floor of the logarithm (to the base two) of ** the specified natural number. ** pre: m>=0 ** @return floor of lg m (we define lg 0 to be -1) */ public static int floorLog2(int m) { int result; if (m == 0) { result = -1; } else { result = 0; while (m != 1) { m = m / 2; result++; } } return result; } /** Calculates the floor of the logarithm (to the base two) of ** the specified natural number. (Recursive version) ** pre: m>=0 ** @return floor of lg m (we define lg 0 to be -1) */ public static int floorLog2Rec(int m) { int result; if (m == 0) { result = -1; } else { result = 1 + floorLog2Rec(m/2); } return result; } /** Calculates the ceiling of the logarithm (to the base two) of ** the specified natural number. ** pre: m >= 0 ** @return ceiling of lg m (we define lg 0 to be -1) */ public static int ceilingLog2(int m) { int result; if (m == 0) { result = floorLog2(0); } else { result = floorLog2(m + m - 1); } return result; } }