알고리즘

문자열/조합 0의 개수 백준 2004번

espossible 2021. 9. 26. 15:51
알고리즘 : 문자열

시간 제한 메모리 제한
2초 128MB

문제

n명의 사람중 m명을 순서에 상관없이 뽑는 경우의 수를 조합이라고 하며 nCm으로 나타낸다.

nCm은 수식으로 n!/m!(n-m)! 으로 구할 수 있다. (5! = 1 2 3 4 5)

n과 m이 주어졌을때 nCm의 끝자리 0의 개수를 출력하는 프로그램을 작성하시오.

입력

첫째 줄에 정수 n,m (0≤m≤n≤2,000,000,000, n≠0)이 들어온다.

출력

n과 m이 주어졌을때 nCm의 끝자리 0의 개수를 출력

예제 입력 1

25 12

예제 출력 1

2

출처

  • 데이터를 추가한 사람: dcrgkev

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

public class Main {
	
	public static void main(String[] args) throws Exception {
		Main main = new Main();
		main.main();
	}

	public void main() throws Exception {
		//System.setIn(new FileInputStream("src/test1/input.txt"));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String line = br.readLine().trim();
		String[] sp = line.split(" ");

		int N = Integer.parseInt(sp[0]);
		int M = Integer.parseInt(sp[1]);

		int twoCnt = calculateKcountOfFatorialN(N, 2) - (calculateKcountOfFatorialN(N-M, 2)+calculateKcountOfFatorialN(M, 2));
		int fiveCnt =  calculateKcountOfFatorialN(N, 5) - (calculateKcountOfFatorialN(N-M, 5)+calculateKcountOfFatorialN(M, 5));
		
		System.out.println(calculateCountOfTen(twoCnt, fiveCnt));
		
		br.close();
	}
	private int calculateCountOfTen(int twoCnt, int fiveCnt) {
		if(twoCnt <= 0 || fiveCnt <= 0) {
			return 0;
		} else {
			return twoCnt > fiveCnt ? fiveCnt : twoCnt;
		}
	}
	private int calculateKcountOfFatorialN(int N, int K) {
		int sum = 0;
		for(long i=K;i<=N;i*=K) {
			sum+=N/i;
		}
		return sum;
	}
}

 

시간 메모리
132ms 14260KB

 


출처

- https://www.acmicpc.net/problem/2004