Algorithm/이분 탐색

BOJ#13706 제곱근

밤이2209 2017. 10. 26. 19:26

BOJ#13706 제곱근



* 문제

https://www.acmicpc.net/problem/13706



* 풀이


이분 탐색, BigInteger 사용





* 나의 코드

https://github.com/stack07142/BOJ/blob/bcbfa3899c5c3acae75e515c8642eddcb3a9067e/BOJ%2313706/src/Main.java


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;

public class Main {

public static void main(String[] args) throws IOException {

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String num = br.readLine();

sqrt(num);
}

static void sqrt(String num) {

BigInteger one = BigInteger.ONE;
BigInteger two = new BigInteger("2");

BigInteger target = new BigInteger(num);

BigInteger left = BigInteger.ONE;
BigInteger right = new BigInteger(num);

BigInteger mid, x;

while (left.compareTo(right) <= 0) {

mid = (left.add(right)).divide(two);
x = mid.multiply(mid);

int ret = x.compareTo(target);
if (ret == 0) {

System.out.println(mid.toString());
break;
} else if (ret == -1) {

left = mid.add(one);
} else if (ret == 1) {

right = mid.subtract(one);
}
}
}
}


'Algorithm > 이분 탐색' 카테고리의 다른 글

BOJ#1300 K번째 수  (1) 2017.10.17
BOJ#2805 나무 자르기  (0) 2017.05.24