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

ByWindow·2022년 3월 17일
0

Algorithm

목록 보기
93/104
post-thumbnail

📝문제

예전에 풀다가 실패했던 문제를 우연히 발견하여 한번 풀어보았다.
수의 맨 뒷자리부터 0이 연속된다는 것은 그만큼 10이 거듭제곱 되어 있다는 것이다.
그래서 나는 에라토스테네스의 체로 소수를 찾았던 것과 비슷한 방법으로
n!을 소인소분해 했을 때 2와 5가 각각 몇 개 있는지 세어보는 방법을 택했고
그 중 작은 것이 답이 된다.

📌코드

package Solving;

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

public class BOJ1676 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());

        int cntTow = 0;

        for(int i = 2; i < n+1; i*=2){
            for(int j = i; j < n+1; j+=i){
                cntTow++;
            }
        }

        int cntFive = 0;

        for(int i = 5; i < n+1; i*=5){
            for(int j = i; j < n+1; j+=i){
                cntFive++;
            }
        }

        System.out.println(Math.min(cntTow, cntFive));
    }
}
profile
step by step...my devlog

0개의 댓글