[BaekJoon] #1676 - 팩토리얼 0의 개수 [Java][C++][Python]
[BaekJoon] #1676 - 팩토리얼 0의 개수 [Java][C++][Python]
1. 아이디어
$N!$의 끝에 붙는 0의 개수는 $N!$을 10으로 나눌 수 있는 횟수이고 $10 = 2 \times 5$이므로 소인수 2의 개수와 5의 개수 중 작은 쪽이다. $N!$에서는 모든 $k$에 대해 $\lfloor N / 2^k \rfloor \ge \lfloor N / 5^k \rfloor$라 2가 5보다 적을 수 없으니 5의 개수만 세면 된다. 5의 배수는 하나마다 5를 하나씩 가지고 그중 25의 배수는 하나를 더, 125의 배수는 또 하나를 더 가지므로 5의 개수는 $\lfloor N / 5 \rfloor + \lfloor N / 25 \rfloor + \lfloor N / 125 \rfloor$이고, $N \le 500$이라 $5^4 = 625$부터는 항이 0이다.
2. 코드
풀이 [Java][C++][Python]
1
2
3
4
5
6
7
8
9
10
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
System.out.println(n / 5 + n / 25 + n / 125);
}
}
1
2
3
4
5
6
7
8
9
10
11
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
cout << n / 5 + n / 25 + n / 125;
}
1
2
3
4
5
6
import sys
input = sys.stdin.readline
n = int(input())
print(n // 5 + n // 25 + n // 125)
This post is licensed under CC BY 4.0 by the author.