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);
    }
}
참고:
'알고리즘 > 백준' 카테고리의 다른 글
| 백준 9613번 - GCD합 (Java 8) (0) | 2022.03.16 | 
|---|---|
| 백준 2004번 - 조합 0의 개수 (Java 8) (0) | 2022.03.15 | 
| 백준 6588번 - 골드바흐의 추측 (Java 8) (0) | 2022.03.15 | 
| 백준 1934번 - 최소공배수 (Java 8) (0) | 2022.03.15 | 
| 백준 2608번 - 최대공약수와 최소공배수 (Java 8) (0) | 2022.03.15 | 
										
									
										
									
										
									
										
									
댓글