How many ways can you pick k items out of a set of n items?
n!
----------
k!*(n-k)!
The Program
/**********************************************
* File: combine.c
* Author: D. Frey
* Date: 8/2/99
* Section: 101
* SSN: 123-45-6789
* EMail: frey@cs.umbc.edu
*
* This program tests a function to compute the
* mathematical combination function
* Combinations(n, k), which gives the number
* of ways to choose a subset of k objects from
* a set of n distinct objects.
**********************************************/
#include
/* Function prototypes */
int Combinations (int n, int k);
int Factorial (int n);
/* Main program */
int main ()
{
int n, k;
/* input n and k from the user */
printf("Enter number of objects in the set (n)? ");
scanf ("%d", &n);
printf("Enter number to be chosen (k)? ");
scanf ("%d", &k);
/* calculate and display ways to choose k from n */
printf("C(%d, %d) = %d\n", n, k, Combinations(n, k));
return 0;
}
/**********************************************
* Function: Combinations
* Usage: ways = Combinations(n, k);
*
* Inputs: n -- the number of distinct objects
* in the set
* k -- the number of objects to choose
* from the set
* Ouput: Number of ways to choose k from n
* see description below
*
* Assumptions:
* 1 <= n
* 1 <= k <= n
*
* Implements the Combinations function, which
* returns the number of distinct ways of choosing
* k objects from a set of n objects. In
* mathematics, this function is often written as
* C(n,k), but a function called C is not very
* self-descriptive, particularly in a language
* which has precisely the same name. Implements
* the formula n!/(k! * (n - k)!)
**********************************************/
int Combinations(int n, int k)
{
int numerator, denominator, ways;
numerator = Factorial (n);
denominator = Factorial (k) * Factorial (n - k);
ways = numerator / denominator;
return (ways);
}
/**********************************************
* Function: Factorial
* Usage: f = Factorial(n);
*
* Input: integer n for which to calculate n!
* Ouput: n! = n * n - 1 * n - 2 * ... * 3 * 2 * 1
**********************************************/
int Factorial (int n)
{
int product, i;
product = 1;
for (i = 1; i <= n; i++)
{
product *= i;
}
return (product);
}
The Sample Run
linux3[97] % a.out
Enter number of objects in the set (n)? 6
Enter number to be chosen (k)? 2
C(6, 2) = 15
linux3[98] % !a
a.out
Enter number of objects in the set (n)? 3
Enter number to be chosen (k)? 2
C(3, 2) = 3
linux3[99] % !a
a.out
Enter number of objects in the set (n)? 12
Enter number to be chosen (k)? 4
C(12, 4) = 495
linux3[100] %