UVA 10023 Square root

先百度看了一下开平方的算法然后用java大数敲的。

把开平方理论看懂就很好写了。http://baike.baidu.com/view/239903.htm?fr=aladdin

import java.math.BigInteger;
import java.util.Scanner;


public class Main {
	public static void solve(BigInteger y){
		String str = "0"+y.toString();
		int i = str.length()%2;
		BigInteger div  = new BigInteger("0");
		BigInteger ans  = new BigInteger("0");
		BigInteger tmp  = new BigInteger("0");
		for(;i < str.length();i+=2){
			tmp = ans.multiply(BigInteger.valueOf(20));
			div = div.multiply(BigInteger.valueOf(100)).add(new BigInteger(str.substring(i,i+2)));
			for(int j = 0; j < 10;j++){
				if(tmp.add(BigInteger.valueOf(j+1)).multiply(BigInteger.valueOf(j+1)).compareTo(div)==1){
					ans = ans.multiply(BigInteger.valueOf(10)).add(BigInteger.valueOf(j));
					tmp = tmp.add(BigInteger.valueOf(j));
					div = div.add(tmp.multiply(BigInteger.valueOf(j)).negate());
					break;
				}
			}
		}
		System.out.println(ans);
	}
	
	public static void main(String[] args) {
		
		Scanner cin = new Scanner(System.in);
		int t = 0;
		t = cin.nextInt();
		for(int i = 0;i < t;i++){
			if(i!=0) System.out.println();
			solve(cin.nextBigInteger());
		}
	}

}


你可能感兴趣的:(UVA 10023 Square root)