code:
#include<stdio.h>
int binomialCoeff(int n, int k)
{
// Base Cases
if (k==0 || k==n)
return 1;
else
return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k);
}
int main()
{
int n = 5, k = 2;
printf("Value of C(%d, %d) is %d ", n, k, binomialCoeff(n, k));
return 0;
}
I think I can understand the base case. When we use 0 for n and k=n the result is 0!/0! which is = 1. So we return 1. Formula
But I can't understand this part of the code:
return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k);
With values of 5 for n and 2 for k I get the result 10. (When replace in the formula).formula But why we use аddition?
And one more thing. Why the program doesn't work when I set "n" and "k" from the keyboard? Like this:
int main()
{
int n,k;
cin>>n;
cin>>k;
printf("Value of C(%d, %d) is %d ", n, k, binomialCoeff(n, k));
return 0;
}
One of the properties of binomial coefficients is that: C(n, k) can be written as C(n-1,k-1) + C(n-1,k) for all 1 <= k <= n-1.
So a C(3,2) = C(2,1) + C(2,2) Or 3 = 2 + 1
This is what is used in the simple recursion example you have shared.
Regarding your second problem, not sure why you should have any problems.