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 ??
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.
A binomial coefficient C(n, k) can be defined as the coefficient of x^k in the expansion of (1 + x)^n.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With