UVA 10023 - Square root(手算平方根)

来源:互联网 发布:菲律宾网络彩票合法吗 编辑:程序博客网 时间:2024/04/29 23:29

题目:UVA 10023 - Square root(手算平方根)

题目链接

题目大意:求给定的一个数的平方根。

解题思路:用二分但是这个数太大了,就超时了。看题接后发现需要用一种手算平方根的算法。

算法: 
先判断这个数是不是偶数位,是的话就第一次取前面的两位数,不是的话第一次就只取前面的一位数来作为被除数。接下来就是两位两位为一节来计算。 
用前一次的计算结果乘上20+一个个位数a再乘上这个a,找到最大的a使得这个式子的结果不大于被除数。 
被除数减去这个结果然后再在尾巴接上那个大数的接下来两位作为新的被除数。 
除数就是在原本除数的尾巴接上这个a作为新的除数。 
重复上面的步骤,直到计算完这个大数的最后两位。最后的除数就是开方数。

代码:

import java.util.*;import java.math.*;import java.io.*;public class Main {    public static BigInteger sqrt(BigInteger ans) {        BigInteger num = BigInteger.ZERO;           BigInteger res = BigInteger.ZERO;        BigInteger div;        String str = "0" + ans.toString();        int len = str.length();        int i = len % 2;        for (; i < len; i += 2) {            num = num.multiply(BigInteger.valueOf(100)).add(new BigInteger(str.substring(i, i + 2)));            div = res.multiply(BigInteger.valueOf(20));            for (int j = 0; j < 10; j++) {                if (div.add(BigInteger.valueOf(j + 1)).multiply(BigInteger.valueOf(j + 1)).compareTo(num) > 0) {                    num = num.subtract(div.add(BigInteger.valueOf(j)).multiply(BigInteger.valueOf(j)));                    res = res.multiply(BigInteger.valueOf(10)).add(BigInteger.valueOf(j));                              break;                }            }        }        return res;    }    public static void main(String args[]) {        Scanner cin = new Scanner(System.in);        int T = cin.nextInt();        while (T > 0) {            BigInteger n = cin.nextBigInteger();            System.out.println(sqrt(n));            T--;            if (T > 0)                System.out.println();        }    }}
0 0