백준/JAVA

[백준/JAVA] 1676번 팩토리얼 0의 개수

누룽지맛치킨 2023. 2. 6. 15:49

1. 문제

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

2. 문제 접근

1) 첫째 줄에 N을 입력받는다.
2) N!의 뒤에 0은 10이 곱해질 때마다 하나씩 추가된다.
3) 10이 곱해지기 위해서는 N!에서 각 정수가 곱해질 때 5와 2가 곱해지면 된다.
4) 5의 배수 사이에는 짝수가 무조건 존재하므로 5의 개수만 구하면 0의 개수를 구할 수 있다.

3. 코드

import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

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());
        int result =0;
        for(int i=5;i<=n;i++) {
            int temp = i;
            while(temp%5==0) {
                result++;
                temp/=5;
            }
        }
        System.out.println(result);
    }
}