Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to generate binomial coefficients

I need to calculate combinations for a number.

What is the fastest way to calculate nCp where n>>p?

I need a fast way to generate binomial coefficients for an polynomial equation and I need to get the coefficient of all the terms and store it in an array.

(a+b)^n = a^n + nC1 a^(n-1) * b + nC2 a^(n-2) * ............ +nC(n-1) a * b^(n-1) + b^n

What is the most efficient way to calculate nCp ??

like image 900
Rajesh Pantula Avatar asked Jun 14 '12 12:06

Rajesh Pantula


People also ask

What is the fastest way to calculate binomial coefficient?

The binomial coefficients are the integers calculated using the formula: (nk)=n!k! (n−k)!. The binomial theorem provides a method for expanding binomials raised to powers without directly multiplying each factor: (x+y)n= nΣk=0 (nk) xn−kyk. Use Pascal's triangle to quickly determine the binomial coefficients.

How do you draw a binomial coefficient?

A binomial coefficient C(n, k) can be defined as the coefficient of x^k in the expansion of (1 + x)^n.

What is the time complexity for binomial coefficient?

Cm = n-1Cm-1 + n-1Cm A similar analysis to that used for the Fibonacci numbers shows that the time complexity using this approach is also the binomial coefficient itself. Each entry takes O(1) time to calculate and there are O(n2) of them. So this calculation of the coefficients takes O(n2) time.


2 Answers

You cau use dynamic programming in order to generate binomial coefficients

You can create an array and than use O(N^2) loop to fill it

C[n, k] = C[n-1, k-1] + C[n-1, k]; 

where

C[1, 1] = C[n, n] = 1 

After that in your program you can get the C(n, k) value just looking at your 2D array at [n, k] indices

UPDATE smth like that

for (int k = 1; k <= K; k++) C[0][k] = 0; for (int n = 0; n <= N; n++) C[n][0] = 1;  for (int n = 1; n <= N; n++)    for (int k = 1; k <= K; k++)       C[n][k] = C[n-1][k-1] + C[n-1][k]; 

where the N, K - maximum values of your n, k

like image 133
Ribtoks Avatar answered Sep 20 '22 08:09

Ribtoks


If you need to compute them for all n, Ribtoks's answer is probably the best. For a single n, you're better off doing like this:

C[0] = 1 for (int k = 0; k < n; ++ k)     C[k+1] = (C[k] * (n-k)) / (k+1) 

The division is exact, if done after the multiplication.

And beware of overflowing with C[k] * (n-k) : use large enough integers.

like image 31
Frédéric van der Plancke Avatar answered Sep 22 '22 08:09

Frédéric van der Plancke