본문 바로가기
알고리즘/프로그래머스(Lv.0)

[프로그래머스] Lv.0 구슬을 나누는 경우의 수

by cejin 2023. 11. 28.

1. 문제

매개변수 : 전체 구슬 개수 balls,  친구에게 나눠줄 구슬 개수 share (share <= balls)

리턴값 : int

힌트 : 서로 다른 n개 중 m개를 뽑는 경우의 수 n! / (n-m)! * m!

 

 

2. 풀이

1. 오류

 

문제 하단에 식까지 나와있어서 간단하겠다 싶었는데 안 돌아갔다.

처음엔 int로, 다음엔 long으로 시도했는데 실패였다.

찾아보니 숫자가 엄청 커지는 게 문제였다. (30!)

 

 

2) 해결방법

 

BigInteger (Java SE 17 & JDK 17)

All Implemented Interfaces: Serializable, Comparable Immutable arbitrary-precision integers. All operations behave as if BigIntegers were represented in two's-complement notation (like Java's primitive integer types). BigInteger provides analogues to all o

docs.oracle.com

 

큰 숫자를 다룰 때는 BigInteger를 쓰면 된다.

 

(1) 생성자

BigInteger bigInt = new BigInteger(int값);

 

(2) 메서드

static BigInteger valueOf(long val)  :  정수를  BigInteger

int intValue() : BigInteger를 정수로

BigInteger add(BigInteger val) : 더하기

BigInteger subract(BigInteger val) : 빼기

BigInteger multiply(BigInteger val) : 곱하기

BigInteger divide(BigInteger val) : 나누기

 

(3) 상수

BigInteger.ONE : BigInteger 1

 

 

* 풀 코드 : https://github.com/cejinn/programmers_lv0/blob/main/basic056.java