#include <iostream>
usingnamespace std;
int recursivebinomial(int, int);
int main()
{
int m = 4;
int n = 2;
cout << "Evaluating the binomial coefficients" << endl;
int h = recursivebinomial(m,n);
cout << h << endl;
return 0;
}
int recursivebinomial(int m, int n)
{
if(m != 0 && n == 0)
return 1;
elseif(m == 0 && n != 0)
return 0;
elsereturn recursivebinomial(--m, --n) + recursivebinomial(--m, n);
}
kev82, i am not sure what you are referring to. Is my program incorrect or the formula that I am using? Because the error is a runtime. Anyways, I figured out what was wrong, and here is the correct code:
#include <iostream>
usingnamespace std;
int recursivebinomial(int, int);
int main()
{
int m = 4;
int n = 2;
cout << "Evaluating the binomial coefficients" << endl;
int h = recursivebinomial(m,n);
cout << h << endl;
return 0;
}
int recursivebinomial(int m, int n)
{
if(n == 0)
return 1;
elseif(m == 0)
return 0;
elsereturn recursivebinomial(--m, --n) + recursivebinomial(m, n + 1);
}
You're causing undefined behavior by using [a variable you're decrementing] twice in the same expression.
Change line 21 to this: return recursivebinomial(m-1, n-1) + recursivebinomial(m-1, n);
You were using the wrong formula, and not catching all the base cases of it. By inserting a print statement you can watch yourself go beyond 0,0 towards the inevitable stack overflow.
No. Save for a few exceptions (the rule is rather complicated and not too important), any expression where a {pre|post}{in|de}crement is applied to x and x appears again in the same expression, has undefined behavior.