#include <stdio.h>
/*
* Compute the number of combinations C(n, r):
*
* C(n, r) = n! / (r! * (n - r)!)
*
* The calculation is performed incrementally to avoid
* computing large factorials.
*/
unsigned long long combinations(unsigned int n, unsigned int r)
{
/* Use symmetry: C(n, r) == C(n, n - r) */
if (r > n - r) {
r = n - r;
}
unsigned long long result = 1;
/*
* Compute:
*
* (n ) (n - 1) ... (n - r + 1)
* -------- * ------- * ... * -----------
* 1 2 r
*/
for (unsigned int i = 0; i < r; ++i) {
result *= (n - i);
result /= (i + 1);
}
return result;
}
int main(void)
{
const unsigned int total_numbers = 33;
const unsigned int chosen_numbers = 7;
unsigned long long total_combinations =
combinations(total_numbers, chosen_numbers);
printf("C(%u, %u) = %llu\n",
total_numbers,
chosen_numbers,
total_combinations);
return 0;
}
/*
run:
C(33, 7) = 4272048
*/