Created
May 21, 2021 11:58
-
-
Save ok3141/845b648ef15b9caf707c177ff433cd05 to your computer and use it in GitHub Desktop.
Mathematics Utils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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