[BaekJoon] #2004 - 조합 0의 개수 [Java][C++][Python]
[BaekJoon] #2004 - 조합 0의 개수 [Java][C++][Python]
1. 아이디어
$\dbinom{n}{m} = \dfrac{n!}{m!(n - m)!}$의 끝자리 0의 개수는 10으로 나눌 수 있는 횟수이고 $10 = 2 \times 5$이므로 소인수 2의 개수와 5의 개수 중 작은 쪽이다. $n$이 최대 2,000,000,000이라 조합 값을 직접 구할 수 없어 소인수의 개수만 계산한다. $n!$에 들어 있는 소인수 $p$의 개수는 $p$의 배수, $p^2$의 배수, $p^3$의 배수, $\ldots$의 개수를 더한 $\lfloor n / p \rfloor + \lfloor n / p^2 \rfloor + \lfloor n / p^3 \rfloor + \cdots$이므로, 분자 $n!$에 들어 있는 $p$의 개수에서 분모 $m!$과 $(n - m)!$에 들어 있는 $p$의 개수를 빼면 조합에 들어 있는 $p$의 개수가 된다. $n!$에서는 2의 개수가 5의 개수보다 적을 수 없지만 조합은 나눗셈이 들어 있어 그 보장이 없으므로($\binom{5}{1} = 5$) 2와 5의 개수를 모두 구해 작은 쪽을 택해야 한다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int cnt2 = countFactor(n, 2) - countFactor(m, 2) - countFactor(n - m, 2);
int cnt5 = countFactor(n, 5) - countFactor(m, 5) - countFactor(n - m, 5);
System.out.println(Math.min(cnt2, cnt5));
}
static int countFactor(int x, int div) {
int cnt = 0;
while (x > 0) {
x /= div;
cnt += x;
}
return cnt;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <bits/stdc++.h>
using namespace std;
int countFactor(int x, int div) {
int cnt = 0;
while (x > 0) {
x /= div;
cnt += x;
}
return cnt;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
int cnt2 = countFactor(n, 2) - countFactor(m, 2) - countFactor(n - m, 2);
int cnt5 = countFactor(n, 5) - countFactor(m, 5) - countFactor(n - m, 5);
cout << min(cnt2, cnt5);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import sys
input = sys.stdin.readline
def count_factor(x, div):
cnt = 0
while x > 0:
x //= div
cnt += x
return cnt
n, m = map(int, input().split())
cnt2 = count_factor(n, 2) - count_factor(m, 2) - count_factor(n - m, 2)
cnt5 = count_factor(n, 5) - count_factor(m, 5) - count_factor(n - m, 5)
print(min(cnt2, cnt5))
This post is licensed under CC BY 4.0 by the author.