문제설명
두 개의 숫자 n,m을 입력받고 n,m의 이항계수의 끝자리의 0의 개수를 출력하는 문제입니다.
작동 순서
1. 숫자 n, m을 입력받습니다.
2. 이항계수를 구하는 방법은 n!/m!*(n-m)!이고 끝자리의 0의 개수를 구하는 방법은 그 수를 소인수 분해했을 때 2의 개수와 5의 개수 중 적은 수이므로 n!의 2의 개수-(m!의 2의 개수+(n-m)!의 2의 개수)와 n!의 5의 개수-(m!의 5의 개수+(n-m)!의 5의 개수)중 작은 수를 출력합니다.
소스코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class 백준_2004번_조합0의개수 {
static int CheckTwo(long num){
int Two=0;
for(long div=2;div<=num;div*=2) {
Two += num / div;
}
return Two;
}
static int CheckFive(long num){
int Five=0;
for(long div=5;div<=num;div*=5) {
Five += num / div;
}
return Five;
}
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String[] input=br.readLine().split(" ");
long n=Integer.parseInt(input[0]), m=Integer.parseInt(input[1]);
int NumOfZero=Math.min(CheckTwo(n)-CheckTwo(m)-CheckTwo(n-m),CheckFive(n)-CheckFive(m)-CheckFive(n-m));
System.out.print(NumOfZero);
}
}
후기
저번에 풀었던 팩토리얼 0의 개수에서는 5의 개수만 체크해도 정답이었는데 이번 문제에서는 2의 개수도 체크해야해서 푸는데 오래걸렸습니다. 비슷한 문제라도 여러가지를 생각하는 법을 배워야 할 것 같습니다.