24h購物| | PChome| 登入
2012-03-26 22:33:54| 人氣1,498| 回應0 | 上一篇 | 下一篇

[UVA][JAVA] 10023 - Square root

推薦 0 收藏 0 轉貼0 訂閱站台

Square root  

The Problem

You are to determinate X by given Y, from expression

The Input

The first line is the number of test cases, followed by a blank line.

Each test case of the input contains a positive integer Y (1<=Y<=101000), with no blanks or leading zeroes in it.
It is guaranteed, that for given Y, X will be always an integer.

Each test case will be separated by a single line.

The Output

For each test case, your program should print X in the same format as Y was given in input.

Print a blank line between the outputs for two consecutive test cases.

Sample Input

1

7206604678144

Sample Output

2684512

就算是 JAVA 也沒有大數開根號, 只好採用二分逼近,
不過會有測資不是完全平方數,
for example
x = 1000 you should output y = 31
這個部份讓我錯了很多 ...

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

public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String x;
BigInteger l, r, m, n;
int t = keyboard.nextInt();
while(t != 0) {
t--;
x = keyboard.next();
n = new BigInteger(x);
l = BigInteger.valueOf(1);
r = BigInteger.valueOf(10).pow(x.length()/2+1);
m = BigInteger.valueOf(0);
while(l.compareTo(r) <= 0) {
m = l.add(r).shiftRight(1);
if(m.multiply(m).compareTo(n) == 1) {
r = m.subtract(BigInteger.valueOf(1));
} else if(m.multiply(m).compareTo(n) == -1) {
l = m.add(BigInteger.valueOf(1));
} else
break;
}
if(m.multiply(m).compareTo(n) > 0)
m = l.subtract(BigInteger.valueOf(1));
System.out.println(m.toString());
if(t != 0)
System.out.println("");
}
}
}
 

台長: Morris
人氣(1,498) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][LCS] 10192 - Vacation
此分類上一篇:[UVA][JAVA] 10183 - How Many Fibs?

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文