백준
백준 11050: 이항 계수 1(java/C)
unhyepnhj
2024. 7. 6. 19:20
문제

풀이
이항 계수는 주어진 집합에서 주어진 개수만큼 순서 없이 뽑는 조합의 가짓수를 말한다.
이항 정리로 전개했을 때 계수 어쩌고... 라고 뜰 텐데 그냥 고등학생 때 확통 순열 조합 하면서 배운 nCr이다.
nCr 공식만 알고 있으면 해당 공식 그대로 이용해 쉽게 풀 수 있다.

팩토리얼을 구하기 위해 팩토리얼 계산 메소드 getFactorial()을 사용하여 풀이했으며, 이는 순환 알고리즘을 이용해 작성할 수 있다.
[JAVA]
늘 그렇듯 BufferedReader 사용
String[] input=in.readLine().split(" ");
readLine()은 한 줄 전체를 읽는 메소드이므로 split()을 이용하여 띄어쓰기 단위로 한 번 나눠 주었다.
Scanner 사용하려면 띄어쓰기 고하지 않고 nextInt로 받으면 된다.
StringTokenizer st = new StringTokenizer(in.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
이렇게 split() 말고 StringTokenizer+nextToken()으로 해도 무방할 듯 하다(import문 주의)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main{
private static int getFactorial(int n) {
if(n<=1) return 1;
else return(n*getFactorial(n-1));
}
public static void main(String[] args) throws IOException{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String[] input=in.readLine().split(" ");
int N=Integer.parseInt(input[0]);
int K=Integer.parseInt(input[1]);
int c=getFactorial(N)/(getFactorial(K)*getFactorial(N-K));
System.out.println(c);
}
}
[C]
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int getFactorial(int n) {
if (n <= 1) return 1;
else return(n * getFactorial(n - 1));
}
int main(void) {
int N, K;
scanf("%d %d", &N, &K);
int c = getFactorial(N) / (getFactorial(K) * getFactorial(N - K));
printf("%d", c);
return 0;
}