백준코딩일기

1676) 팩토리얼 0의 개수 - JAVA

nari___ 2020. 1. 15. 15:02

 

https://www.acmicpc.net/problem/1676

 

1676번: 팩토리얼 0의 개수

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

www.acmicpc.net

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.*;
public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        // 입력받을 수 => N!
        long N = Integer.parseInt(br.readLine());
        // 0의 갯수를 담을 변수
        int cnt=0;
        // 뒤에서부터 나오는 0의 갯수를 찾으려면 전체 펙토리얼(!)에 5가 몇번 나오는지 확인하면 됨
        // 그래서 index는 5부터 시작하고 N과 같거나 작을 때까지 확인
        // 25 50 75... 처럼 5가 2개씩 들어가는 경우가 있음
        // 그래서 index가 n보다 작거나 같을 동안에는
        // index를 5의 배수로 증가시키면서 
        // N을 index로 나눈 값을 변수에 담아준다.
        for(int index = 5; index<=N; index*=5) {
            cnt += N/index;
        }
        bw.write(cnt + "\n");
    }
} cs