n_choose_k

Ali Hamdi Ali Fadel · @AliOsm · almost 3 years

Calculates N choose K, N! / (K! * (N - K)!), in a mathematical operations efficient way.

def n_choose_k(n, k)
raise ArgumentError.new 'K should be less than or equal to N' if k > n
result = 1
a = n - k + 1
b = 1
while a <= n do
result = result * a / b
a += 1
b += 1
end
result
end
1 · 0 · 1