본문 바로가기

BigInteger 클래스

큰 정수에 대해 연산할 때 유용한 클래스.



1. Fields


public static final BigInteger ONE;

public static final BigInteger TEN;

public static final BigInteger ZERO;


각각 값이 1, 10, 0인 BigInteger 객체다. 이 상수 필드들은 연산 시 유용하게 사용된다.

BigInteger 클래스의 연산 메소드는 BigInteger 객체를 매개값으로 받아 연산하기 때문이다.






2. Constructors


① public BigInteger(byte[] val)


val의 각 요소를 1바이트로 간주해 little-endian 방식으로 채운 값을 반환한다.

예를 들어 val = {1, 0}으로 초기화되었을 경우 BigInteger 객체는 0000000100000000의 값(256)을 갖고, val = {3, 4}로 초기화되었을 경우 BigInteger 객체는 0000001100000100의 값(772)을 갖는다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.math.BigInteger;
 
public class Example {
 
    public static void main(String[] args) {
        byte[] val1 = {10};
        BigInteger bi= new BigInteger(val1);
        System.out.println(bi);
        
        byte[] val2 = {34};
        bi = new BigInteger(val2);
        System.out.println(bi);
 
    }
 
}
cs




public BigInteger(String val)


val을 10진수 정수로 변환한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
import java.math.BigInteger;
 
public class Example {
 
    public static void main(String[] args) throws Exception {
        BigInteger bi = new BigInteger("1200000000000000000000000000000000000000");
        BigInteger result = bi.divide(new BigInteger("10000000000000000000000000000000"));
        
        System.out.println(result);
        
    }
 
}
cs



 divide() 메소드는 주어진 BigInteger 객체( val )의 값으로 자기 자신( this )의 값을 나눈 값을 갖는 BigInteger 객체를 반환하는 메소드다.



public BigInteger(String val, int radix) 


val을 radix진수 정수로 인식해 변환한다.


<2진수>

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.math.BigInteger;
 
public class Example {
 
    public static void main(String[] args) {
        String val = "100";
        BigInteger bi = new BigInteger(val, 2);
 
        System.out.println(bi);
 
    }
 
}
cs




<8진수>

1
2
3
4
5
6
7
8
9
10
11
12
13
import java.math.BigInteger;
 
public class Example {
 
    public static void main(String[] args) {
        String val = "100";
        BigInteger bi = new BigInteger(val, 8);
 
        System.out.println(bi);
 
    }

}
cs






3. Methods



① 일반 연산


Modifer and type

method

설명

 public BigInteger

 add(BigInteger val)

 자신의 값과 val의 값을 더한 결과(this + val)를

 BigInteger 객체로 반환

 public BigInteger

 subtract(BigInteger val)

 this - val 반환

 public BigInteger

 multiply(BigInteger val)

 this * val 반환

 public BigInteger

 divide(BigInteger val)

 this / val (몫) 반환

 public BigInteger

 mod(BigInteger val)

 this % val 반환


이때 반환되는 것은 결과값 자체가 아니라 그 결과값을 갖는 새로운 BigInteger 객체다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.math.BigInteger;
 
public class Example {
 
    public static void main(String[] args) {
        BigInteger bi = new BigInteger("3");
        BigInteger val = new BigInteger("2");
        
        System.out.println("add: " + bi.add(val));
        System.out.println("subtract: " + bi.subtract(val));
        System.out.println("multiply: " +  bi.multiply(val));
        System.out.println("divide: " +  bi.divide(val));
        System.out.println("mod: " +  bi.mod(val));
            
    }
 
}
cs




② 특수 연산


Modifier and type

 method

설명 

 public BigInteger 

 pow(int exponent) 

 this^exponent

 public BigInteger

 modPow(BigInteger exponent, BigInteger m)

 (this^exponent) mod m

 public BigInteger 

 gcd(BigInteger val)

 this와 val의 최대공약수

 public BigInteger 

 abs()

 this의 절댓값


마찬가지로 반환되는 것은 결과값 자체가 아니라 그 결과값을 갖는 새로운 BigInteger 객체다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import java.math.BigInteger;
 
public class Example {
 
    public static void main(String[] args) {
        BigInteger bi1 = new BigInteger("2");
        BigInteger bi2 = new BigInteger("42");
        BigInteger bi3 = new BigInteger("-37");
        
        System.out.println("2³ = " + bi1.pow(3));
        System.out.println("2³ % 5 = " + bi1.modPow(new BigInteger("3"), new BigInteger("5")));
        System.out.println("42와 32의 최대 공약수: " + bi2.gcd(new BigInteger("32")));
        System.out.println("-37의 절대값: " + bi3.abs());
            
    }
 
}
cs




③ 비트 연산


Modifier and type

method

설명

 public BigInteger

 and(BigInteger val)

 자신의 값과 val의 값을 and 연산한 결과(this & val)를  

 BigInteger 객체로 반환

 public BigInteger

 or(BigInteger val)

 this | val

 public BigInteger

 not()

 ~this

 public BigInteger

 xor(BigInteger val)

 this ^ val

 public BigInteger

 shiftLeft(int n)

 this << n

 public BigInteger

 shiftRight(int n)

 this >> n


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.math.BigInteger;
 
public class Example {
 
    public static void main(String[] args) {
        BigInteger bi1 = new BigInteger("91"); //00000000 01011011
        BigInteger bi2 = new BigInteger("45"); //00000000 00101101
        
        System.out.println("91 and 45: " + bi1.and(bi2));    //00000000 00001001: 9
        System.out.println("91 or 45: " + bi1.or(bi2));      //00000000 01111111: 127
        System.out.println("not 91: " + bi1.not());          //11111111 10100100: -92
        System.out.println("not 45: " + bi2.not());          //11111111 11010010: -46
        System.out.println("91 xor 45: " + bi1.xor(bi2));    //00000000 01110110: 118
        System.out.println("91 << 1: " + bi1.shiftLeft(1));  //00000000 10110110: 182
        System.out.println("45 >> 1: " + bi2.shiftRight(1)); //00000000 00010110: 22
    }
 
}
cs




④ 비교 연산


 Modifier and type

 method

 설명

 public boolean

 eqauls(Object x)

 자신의 값과 x의 값 비교

 public BigInteger

 min(BigInteger val)

 자신의 값과 val의 값 중 값이 작은 객체 반환

 public BigInteger

 max(BigInteger val)

 자신의 값과 val의 값 중 값이 큰 객체 반환

 public int

 compareTo(BigInteger val)

 this > val이면 1, this == val이면 0, this < val이면 -1 반환


String등의 다른 객체들과 마찬가지로 BigInteger 역시  ==  연산자로 비교할 경우 제대로 비교되지 않는다.  ==  연산자는 값이 아닌 참조를 비교하기 때문에  equals  메소드로 비교해야 제대로 비교할 수 있다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.math.BigInteger;
 
public class Example {
 
    public static void main(String[] args) {
        BigInteger bi1 = new BigInteger("3"); 
        BigInteger bi2 = new BigInteger("3"); 
        BigInteger bi3 = new BigInteger("5"); 
        
        System.out.println("bi1 == bi2: " + (bi1 == bi2));
        System.out.println("bi1.eqauls(bi2): " + bi1.equals(bi2));
        System.out.println("bi2.equals(bi3): " + bi2.equals(bi3));
        System.out.println("min: " + bi1.min(bi3));
        System.out.println("max: " + bi1.max(bi3));
        System.out.println("bi3.compareTo(bi1): " + bi3.compareTo(bi1));
        System.out.println("bi1.compareTo(bi2): " + bi1.compareTo(bi2));
        System.out.println("bi1.compareTo(bi3): " + bi1.compareTo(bi3));    
    }
    
}
cs




⑤ 값 반환


 Modifier and type

 method

 설명

 public XXX

 XXXValue

 XXX형으로 변환해 반환

 public XXX

 XXXValueExact

 XXX형으로 변환해 반환하되 현재 BigInteger 객체의 값이 

 XXX형의 범위를 벗어나는 값일 경우 

 ArithmeticException을 발생시킨다.


여기서 XXX는 기본 자료형(byte, char, short, int, float, double)이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.math.BigInteger;
 
public class Example {
 
    public static void main(String[] args) {
        BigInteger bi1 = new BigInteger("3"); 
        double n1 = bi1.doubleValue(); 
        BigInteger bi2 = new BigInteger("12143415134123141241341231413524");
        
        System.out.println("n1: " + n1);
        
        try {
            int n2 = bi2.intValueExact();
            System.out.println("n2: " + n2);
        } catch(ArithmeticException e) {
            System.out.println("Exception: " + e.getMessage());
        } finally {
            System.out.println("Value is too big!");
        }
        
    }
    
}
cs


'Programming > Java' 카테고리의 다른 글

Managed code  (0) 2019.07.04
IO 입출력  (0) 2019.05.23
자바에서의 배열 선언 및 초기화  (0) 2019.05.08
용어 정리  (0) 2019.04.08
[과제] 호텔 예약 프로그램  (0) 2019.04.08