![[백준 / BOJ] 1676번 팩토리얼 0의 개수 (C++, Python)](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FQOVZF%2FbtrJrRkvUCZ%2FQmkeSLFQK0beJBKik3CJ7K%2Fimg.png)
[백준 / BOJ] 1676번 팩토리얼 0의 개수 (C++, Python)◎ 자료구조와 알고리즘/백준(BOJ) 문제풀이2022. 6. 13. 22:34
Table of Contents
반응형
링크 : https://www.acmicpc.net/problem/1676
1676번: 팩토리얼 0의 개수
N!에서 뒤에서부터 처음 0이 아닌 숫자가 나올 때까지 0의 개수를 구하는 프로그램을 작성하시오.
www.acmicpc.net
문제

문제 풀이
나의 수학실력에 다시 한번 감탄하게 된 문제다. 분명 난이도는 실버 5인데 풀리지가 않아서..
당연하게도 N이 500까지이므로 N!을 직접 구해 해결하는 방법은 불가능하다. 이 문제의 핵심은 뒤에 0이 나오는 경우는 10이 곱해졌을 때라는 것을 알아차리는데에 있다. 그렇다면 0의 개수는 어떻게 구할까?
10의 0의 갯수는 1개이고, 이는 2 x 5다.
100에서 0의 갯수는 2개이고, 이는 2 x 2 x 5 x 5다.
200에서 0의 갯수는 2개이고, 이는 2 x 2 x 2 x 5 x 5다.
1000에서 0의 갯수는 3개이고, 이는 2 x 2 x 2 x 5 x 5 x 5다.
요점은 10이 몇번 곱해졌는지를 알아야 하고, 이는 소인수분해 했을 때 5의 개수와 같다. (2보다 5가 적게 나오기 때문에)
그러므로 N!은 N * (N-1) * (N-2) ...와 같으니 N을 입력받았을 때 1부터 N까지 각각의 수마다 5가 얼마나 나오냐를 체크해주면 된다.
+) 파이썬 코드를 찾아보던 중 이 분의 풀이가 신박한 것 같아 첨부해봅니다.
C++ 코드 전문
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <iostream> | |
#include <vector> | |
void init() { | |
std::ios_base::sync_with_stdio(false); | |
std::cin.tie(nullptr); | |
std::cout.tie(nullptr); | |
} | |
int main() { | |
init(); | |
int N, res = 0; | |
std::cin >> N; | |
for (int i = 1; i <= N; ++i) { | |
int cnt = i; | |
while (cnt >= 1) { | |
if (cnt % 5 == 0) { | |
res++; | |
cnt /= 5; | |
} | |
else | |
break; | |
} | |
} | |
std::cout << res; | |
return 0; | |
} |
Python 코드 전문
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
input = sys.stdin.readline | |
N = int(input()) | |
res = 0 | |
for i in range(1, N + 1): | |
cnt = i | |
while cnt >= 1: | |
if cnt % 5 == 0: | |
res += 1 | |
cnt //= 5 | |
else: | |
break | |
print(res) |
소감
수학은 너무.. 어렵다..
반응형
'◎ 자료구조와 알고리즘 > 백준(BOJ) 문제풀이' 카테고리의 다른 글
[백준 / BOJ] 15649번 N과 M (1) (C++, Python) (0) | 2022.07.07 |
---|---|
[백준 / BOJ] 2004번 조합 0의 개수 (C++, Python) (0) | 2022.06.20 |
[백준 / BOJ] 9375번 패션왕 신해빈 (C++, Python) (0) | 2022.06.12 |
[백준 / BOJ] 1010번 다리 놓기 (C++, Python) (0) | 2022.06.12 |
[백준 / BOJ] 11051번 이항 계수 2 (C++, Python) (0) | 2022.06.10 |
@Reo :: 코드 아카이브
자기계발 블로그