Created
October 24, 2013 15:16
-
-
Save gubatron/7139070 to your computer and use it in GitHub Desktop.
untested - source Faruk Akgul -> http://faruk.akgul.org/blog/javas-missing-algorithm-biginteger-sqrt/
This file contains hidden or 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
| /** Java's BigInteger doesn't have a squared root function, sigh */ | |
| public static BigInteger sqrt(BigInteger n) { | |
| BigInteger a = BigInteger.ONE; | |
| BigInteger b = new BigInteger(n.shiftRight(5).add(new BigInteger("8")).toString()); | |
| while(b.compareTo(a) >= 0) { | |
| BigInteger mid = new BigInteger(a.add(b).shiftRight(1).toString()); | |
| if(mid.multiply(mid).compareTo(n) > 0) b = mid.subtract(BigInteger.ONE); | |
| else a = mid.add(BigInteger.ONE); | |
| } | |
| return a.subtract(BigInteger.ONE); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment