If I understand your question correctly, you are trying to compute the number of ways to
choose k
different items out of n
. That number is given by the "Binomial coefficient" C(n, k)
For example,
the number of possibilities to choose 4 different numbers out of 1, ..., 7 is
C(7, 4) = 35
.
The binomial coefficient can be computed without actually creating all possible combinations as
n * (n-1) * (n-2) * ... * (n-k+1)
C(n, k) = ----------------------------------
1 * 2 * 3 * ... * k
ADDED: (In response to your comment) It is not necessary to compute factorials in
order to compute C(n, k)
. In other words, one would normally not use the formula
C(n, k) = n! / (k! * (n-k)!)
because the factorials get quite large.
Instead you use the above expression in the form
n (n-1) (n-2) (n-k+1)
C(n, k) = - * ----- * ----- * ... * -------
1 2 3 k
A simple implementation could look like this:
long long int choose(int n, int k)
{
if (k < 0 || k > n)
return 0;
long long int result = 1;
// Use the fact that C(n, k) == C(n, n-k) to reduce k:
if (k > n - k)
k = n - k;
for (int i = 1; i <= k; i++) {
result = (result * (n+1-i)) / i;
}
return result;
}
Of course this can also overflow if the numbers get too large. But (since long long int
has at least 64 bit) this is sufficient to compute all binomial coefficients up to n = 60
.