백준
[백준 7489] 팩토리얼 JAVA
오은이
2024. 11. 7. 09:50
기존에 작성한 코드
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int[] n = new int[t];
for (int i = 0; i < t; i++) {
n[i] = sc.nextInt();
}
String[] a = new String[t];
for (int i = 0; i < n.length; i++) {
a[i] = Integer.toString(pac(n[i])).replaceAll("0+$", "");
//a[i] = a[i].replaceAll("0+$", "");
}
for (int i = 0; i < a.length; i++) {
System.out.println(a[i].charAt(a[i].length()-1));
}
}
static int pac(int n) {
if(n < 2) {
return n;
}
return n*pac(n-1);
}
}
결과는 런타임 에러..
이것저것 시도해보다 보니 int형보다 큰 숫자가 들어가서 그렇다고 한다.
새로 작성한 코드
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int[] n = new int[t];
for (int i = 0; i < t; i++) {
n[i] = sc.nextInt();
}
String[] a = new String[t];
for (int i = 0; i < n.length; i++) {
a[i] = pac(n[i]).toString();
a[i] = a[i].replaceAll("0+$", "");
}
for (int i = 0; i < a.length; i++) {
System.out.println(a[i].charAt(a[i].length()-1));
}
}
static BigInteger pac(int n) {
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
}
빅인티저 BigInteger는 처음 이번 계기로 처음 알게되었다.
int와 long은 크기 제한이 있는 기본형 타입이며, BigInteger는 그 범위에 제한이 없고 매우 큰 정수를 처리할 수 있다는 장점이 있다.
Type | 최소값 | 최대값 |
int | -2,147,483,648 (-2^31) | 2,147,483,647 (2^31 - 1) |
long | -9,223,372,036,854,775,808 (-2^63) | 9,223,372,036,854,775,807 (2^63 - 1) |
BigInteger | 시스템 메모리에 의존 (이론상 무제한) | 시스템 메모리에 의존 (이론상 무제한) |