Problema
The binomial coefficient C(n, k), read "n choose k", is the number of ways to pick k items from n different items when order does not matter. The formula n! / (k! (n − k)!) overflows quickly if you compute the factorials first, so build the answer step by step or use Pascal's rule C(n, k) = C(n − 1, k − 1) + C(n − 1, k).
Implement binomial_coefficient(n, k).
Input
n: The number of items.
k: How many to choose.
Output
Return C(n, k). If k > n there is no way to choose, so return 0.
Restricciones
0 ≤ n ≤ 66
0 ≤ k ≤ 100
Ejemplos
Entrada:
n = 5
k = 2
Salida esperada:
expected = 10
Entrada:
long long n = 5;
long long k = 2;
Salida esperada:
long long expected = 10;
Entrada:
long n = 5;
long k = 2;
Salida esperada:
long expected = 10;
Explicación
The pairs from 5 items number 5 × 4 / 2 = 10.
Entrada:
n = 6
k = 0
Salida esperada:
expected = 1
Entrada:
long long n = 6;
long long k = 0;
Salida esperada:
long long expected = 1;
Entrada:
long n = 6;
long k = 0;
Salida esperada:
long expected = 1;
Explicación
There is exactly one way to choose nothing: 1.
Cómo abordarlo
Inténtalo primero por tu cuenta y luego abre las pistas una a una.
Pista 1
Factorials of numbers above 20 do not fit in 64 bits, so avoid them.
Pista 2
One row of Pascal's triangle can be updated in place from right to left.
Pista 3
C(n, k) equals C(n, n − k), and it is 0 when k > n.
Complejidad esperada
O(n · k) time, O(k) extra space
Referencias
Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.