Skip to content

Commit

Permalink
optimize MathUtil.integerLogarithm
Browse files Browse the repository at this point in the history
  • Loading branch information
morj committed May 19, 2017
1 parent b319c18 commit 3e900bb
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 20 deletions.
23 changes: 3 additions & 20 deletions utils/src/main/java/jetbrains/exodus/util/MathUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,33 +15,16 @@
*/
package jetbrains.exodus.util;

import java.util.Arrays;

public class MathUtil {

private static final int POWERS_OF_2[];

static {
POWERS_OF_2 = new int[31];
int power = 1;
for (int i = 0; i < POWERS_OF_2.length; ++i) {
POWERS_OF_2[i] = power;
power <<= 1;
}
}

private MathUtil() {
}

/**
* @param i integer
* @return discrete logarithm of specified integer base 2
*/
public static int integerLogarithm(final int i) {
int result = Arrays.binarySearch(POWERS_OF_2, i);
if (result < 0) {
result = ~result;
if (i <= 0) {
return 0;
}
return result;
return Integer.SIZE - Integer.numberOfLeadingZeros(i - 1);
}
}
35 changes: 35 additions & 0 deletions utils/src/test/java/jetbrains/exodus/util/MathTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* Copyright 2010 - 2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.util;

import org.junit.Assert;
import org.junit.Test;

public class MathTest {

@Test
public void testLog() {
int power = 1;
int expected = 0;
for (int i = 0; i < 10000; i++) {
Assert.assertEquals(expected, MathUtil.integerLogarithm(i));
if (i == power) {
power <<= 1;
expected++;
}
}
}
}

0 comments on commit 3e900bb

Please sign in to comment.