Skip to content

Instantly share code, notes, and snippets.

@ok3141
Created May 21, 2021 11:58
Show Gist options
  • Save ok3141/845b648ef15b9caf707c177ff433cd05 to your computer and use it in GitHub Desktop.
Save ok3141/845b648ef15b9caf707c177ff433cd05 to your computer and use it in GitHub Desktop.
Mathematics Utils
public class MathUtils {
@SuppressWarnings("ManualMinMaxCalculation")
public static int isqrt(int s) {
int x0, x1 = 1;
int d0, d1 = s;
do {
d0 = d1;
x0 = x1;
x1 = (x0 + s / x0) / 2;
d1 = x1 > x0 ? x1 - x0 : x0 - x1;
} while (d1 < d0);
return x0 < x1 ? x0 : x1;
}
}
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class MathUtilsTest {
@Test
public void test_isqrt() {
for (int i = 0; i < 100_000_000; ++i) {
int r = MathUtils.isqrt(i);
assertTrue(r * r <= i);
assertTrue((r + 1L) * (r + 1L) > i);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment