CPlay/bincoef.c

38 lines
1 KiB
C

#include <stdio.h>
/**
* @brief Computes the binomial coefficient "n choose k" (nCk).
*
* This function calculates the number of ways to choose k elements from a set
* of n elements without repetition and without order. It uses an efficient
* multiplicative approach to avoid large intermediate factorials.
*
* @param n The total number of elements.
* @param k The number of elements to choose.
* @return The computed binomial coefficient (n choose k), or 0 if k > n.
*/
unsigned long long binomial_coefficient(unsigned int n, unsigned int k);
unsigned long long binomial_coefficient(unsigned int n, unsigned int k) {
if (k > n)
return 0;
if (k == 0 || k == n)
return 1;
if (k > n - k)
k = n - k;
unsigned long long result = 1;
for (unsigned int i = 1; i <= k; ++i) {
result *= n - (k - i);
result /= i;
}
return result;
}
int main() {
unsigned int n = 10, k = 3;
printf("C(%u, %u) = %llu\n", n, k, binomial_coefficient(n, k));
return 0;
}