Factorial, combinations, & permutations

C

Public Domain

Calculate factorials, combinations, & permutations in C

Download (right click, save as, rename as appropriate)

Embed

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#define nCr(n, r) (factorial(n) / factorial((n)-(r)) / factorial(r))
 /* number of combinations of `n` elements taken `r` at a time */

#define nPr(n, r) (factorial(n) / factorial((n)-(r)))
 /* number of permutations of `n` elements taken `r` at a time */

int factorial(int x) {
 int fac = 1;
 for (int i=2; i<=x; i++) fac *= i;
 return fac;
}