728x90
반응형
알고리즘 문제를 풀다보면 제곱근에 대한 문제가 종종 있습니다. 흔히 사용하는 math 의 pow 로 해결이 불가능 한 경우가 있습니다. 1024 이상의 제곱근을 사용하면 오류가 발생하거나 엉뚱한 숫자가 나타납니다. 이때 사용하는 것이 BigInteger 의 pow 입니다.
아래는 BigInteger를 이용한 제곱근을 구하는 방법입니다. 그리고 나머지를 구해주는 remainder 까지 사용해 보았습니다.
package study.basic;
import java.math.BigInteger;
public class Big_Integer {
public static void main(String[] args) {
BigInteger big1, result;
big1 = new BigInteger("2");
int exponent=1245;
result = big1.pow(exponent);
String str = big1 + "^" + exponent + " = " + result;
System.out.println(str);
int i = 1000000007;
System.out.println( result.remainder(BigInteger.valueOf(i)));
}
}
시험에 종종나오는 큰수의 경우 BigInteger를 사용하여 처리하면 간단히 구현이 가능합니다. 사용법을 꼭 숙지하십시오.
나머지 연산에 대한 내용은 아래 블로그를 참고하세요.
https://kkh0977.tistory.com/161
728x90
반응형