Java大数开根号板子

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Cymbals/article/details/82716782

收藏。

public static BigInteger bigSqrt(String s) {
        BigInteger remain = BigInteger.ZERO;
        BigInteger odd = BigInteger.ZERO;
        BigInteger ans = BigInteger.ZERO;
        int group = 0, k = 0;
        if (s.length() % 2 == 1) {
            group = s.charAt(0) - '0';
            k = -1;
        } else {
            group = (s.charAt(0) - '0') * 10 + s.charAt(1) - '0';
            k = 0;
        }
        for (int j = 0; j < (s.length() + 1) / 2; j++) {
            if (j != 0)
                group = (s.charAt(j * 2 + k) - '0') * 10 + s.charAt(j * 2 + k + 1) - '0';
            odd = BigInteger.valueOf(20).multiply(ans).add(BigInteger.ONE);
            remain = BigInteger.valueOf(100).multiply(remain).add(BigInteger.valueOf(group));
            int count = 0;
            while (remain.compareTo(odd) >= 0) {
                count++;
                remain = remain.subtract(odd);
                odd = odd.add(BigInteger.valueOf(2));
            }
            ans = ans.multiply(BigInteger.TEN).add(BigInteger.valueOf(count));
        }
        return ans;
    }

猜你喜欢

转载自blog.csdn.net/Cymbals/article/details/82716782