본문 바로가기
알고리즘/백준

백준 1676번 - 팩토리얼 0의 개수 (Java 8)

by latissimus 2022. 3. 15.

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

 

1676번: 팩토리얼 0의 개수

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

www.acmicpc.net

코드 :

import java.io.BufferedReader;
import java.io.IOException;
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 twoCount = 0;
        int fiveCount = 0;


        for (int i = 1; i <=N; i++) {
            int temp = i;
            while(temp % 5 == 0){
                temp/= 5;
                fiveCount++;
            }
            while(temp % 2 == 0){
                temp/= 2;
                twoCount++;
            }
        }
        System.out.println(Math.min(fiveCount,twoCount));
    }
}

수정 : 5만 체크하면 되는건지 몰랐다.

import java.io.BufferedReader;
import java.io.IOException;
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 fiveCount = 0;


        for (int i = 1; i <=N; i++) {
            int temp = i;
            while(temp % 5 == 0){
                temp/= 5;
                fiveCount++;
            }
        }
        System.out.println(fiveCount);
    }
}

 

아래에 참고 글을 자세히 보니 양이 많아지면 훨씬 효율적인 방법이 있었다. 5만 세기위해서, 5의 배수만 완전히 고려하는 방법이다.

import java.io.BufferedReader;
import java.io.IOException;
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 fiveCount = 0;

        int num = N;

        while(num >= 5){
            fiveCount += num/5;
            num /=5;
        }

        System.out.println(fiveCount);
    }
}

 

참고:

https://st-lab.tistory.com/165

댓글