Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the Amount of Combinations

Cheers,

I know you can get the amount of combinations with the following formula (without repetition and order is not important):

// Choose r from n  n! / r!(n - r)!

However, I don't know how to implement this in C++, since for instance with

n = 52  n! = 8,0658175170943878571660636856404e+67

the number gets way too big even for unsigned __int64 (or unsigned long long). Is there some workaround to implement the formula without any third-party "bigint" -libraries?

like image 990
nhaa123 Avatar asked Dec 03 '09 08:12

nhaa123


People also ask

How do you calculate the number of possible combinations?

Combinations are a way to calculate the total outcomes of an event where order of the outcomes does not matter. To calculate combinations, we will use the formula nCr = n! / r! * (n - r)!, where n represents the total number of items, and r represents the number of items being chosen at a time.

How many combinations of 5 items are there?

So we say that there are 5 factorial = 5! = 5x4x3x2x1 = 120 ways to arrange five objects.

How many combinations of 3 items are there?

if you have 3 items and want the different combinations of every set, but NOT the 0 possibility then you can use 23−1=7; if you want to know the possibilities of the 7 in sets then you can use the similar formula 27−1=127.


1 Answers

Here's an ancient algorithm which is exact and doesn't overflow unless the result is to big for a long long

unsigned long long choose(unsigned long long n, unsigned long long k) {     if (k > n) {         return 0;     }     unsigned long long r = 1;     for (unsigned long long d = 1; d <= k; ++d) {         r *= n--;         r /= d;     }     return r; } 

This algorithm is also in Knuth's "The Art of Computer Programming, 3rd Edition, Volume 2: Seminumerical Algorithms" I think.

UPDATE: There's a small possibility that the algorithm will overflow on the line:

r *= n--; 

for very large n. A naive upper bound is sqrt(std::numeric_limits<long long>::max()) which means an n less than rougly 4,000,000,000.

like image 111
Andreas Brinck Avatar answered Sep 18 '22 16:09

Andreas Brinck