Binomial Coefficient in C
A combination is the number of ways in which $r$ things taken from a total of $n$ distinguishable items can be arranged, without order.
The below image illustrates the number of ways in which three different circles (red, yellow and black) can be combined, taken two at a time. It is 3.
The combination of $n$ things taken $r$ at a time is denoted by $^{n} \text{C}_{r}$ and the formula for obtaining it is
$^{n} \text{C}_{r} = \frac{n!}{r!(n-r)!}$
This is known as the binomial coefficient, and it occurs as coefficients of $x$ in the expansion of the binomial $(1 + x)^{n}$.
$(1 + x)^{n} = ^{n} \text{C}_{0} + ^{n} \text{C}_{1}x + ^{n} \text{C}_{2}x^{2} + ... + ^{n} \text{C}_{n}x^{n}$
Below is the C program for compuuting the binomial coefficient based on the above formula $^{n} \text{C}_{r} = \frac{n!}{r!(n-r)!}$.
#include <stdio.h>
unsigned long nCr(unsigned short n, unsigned short r);
unsigned long factorial(unsigned short int);
int main() {
unsigned short int n, r;
printf("Enter n: ");
scanf("%hu", &n);
printf("Enter r: ");
scanf("%hu", &r);
printf("%huC%hu: %lu", n, r, nCr(n,r));
printf("\n");
return 0;
}
unsigned long nCr(unsigned short n, unsigned short r) {
return factorial(n)/(factorial(r)*factorial(n-r));
}
unsigned long factorial(unsigned short n) {
unsigned long f;
if(n == 0 || n == 1)
return 1;
else
f = n * factorial(n-1);
return f;
}