본문 바로가기

Algorithm/Math

[C++] 백준 1676번 : 팩토리얼 0의 개수 (S3)

#문제

www.acmicpc.net/problem/1676

 

1676번: 팩토리얼 0의 개수

N!에서 뒤에서부터 처음 0이 아닌 숫자가 나올 때까지 0의 개수를 구하는 프로그램을 작성하시오.

www.acmicpc.net

#풀이 & 학습한 내용

뒤에 0이 붙는 건 2와 5의 곱에 의해 나타난다. 그리고 2의 개수보다 5의 개수가 항상 적기 때문에 5의 개수만 세어주면 된다. 이때 처음에 간과한 것이 5로 나누어 떨어질 때 답에 1을 증가시켜준 것이다. 만약 25일 경우에는 5가 2개 들어있으므로 답에 2를 더해줘야 한다.

 

#소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
#include<algorithm>
 
using namespace std;
 
int main(void) {
    int N;
    cin >> N;
    int ans = 0;
    for (int i = 1; i <= N; i++) {
        int t = i;
        if (t % 5 == 0) {
            while (t % 5 == 0) {
                ans++;
                t /= 5;
            }
        }
    }
    cout << ans << '\n';
}
cs

 

★개선된 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
#include<algorithm>
 
using namespace std;
 
int main(void) {
    int N;
    cin >> N;
    int ans = 0;
    for (int i = 5; i <= N; i *= 5) {
        ans += N / i;
    }
    cout << ans << '\n';
}
cs

 

github.com/HoYoungChun/BOJ_algorithm/blob/master/Math/BOJ_1676.cpp

 

HoYoungChun/BOJ_algorithm

Baekjoon Online Judge problem solving by C++. Contribute to HoYoungChun/BOJ_algorithm development by creating an account on GitHub.

github.com