This is my first post and I'm not sure how the formatting works, but this is my code. When I run the nCr function it will run for a second then stop responding. My factorial function works, but when I add in the nCr function it doesn't work.
#include <iostream>
usingnamespace std;
int nChooser = 0;
int nCr(int p, int p2, int nChooser);
int factorial(int i);
int pascal(int row, int element);
int main()
{
cout << " Pascal Triangle" << endl;
cout << "====================" << endl;
cout << nCr(2,2,0) << endl;
/*for(int i = 0, k = 0; i <= 15; i++, k++)
{
}*/
}
int pascal(int row, int element, int pas)
{
nCr(row,element,0);
return pas;
}
int nCr(int p, int p2, int nChooser)
{
nChooser = factorial(p)/(factorial(p2)*factorial(p - p2));
return nChooser;
}
int factorial(int i)
{
if (i <= 1)
return i;
return (i * factorial(i - 1));
}
I copied this in to a blank project and it actually stops responding right away for me, as soon as it runs line 43. The only way I could actually get it to run, was with passing different numbers to the function,
i.e. nCr( 2, 3, 0 ), which always resulted in the return being 0.
My math isn't amazing, so I don't actually know why. But I was getting a error warning about line 13, and the function having to divide by 0.
What vin said. By returning 'i', your call of factorial(p-p2) (= fact(0)) returns 0, making the denominator of nChooser 0, making for divide-by-zero errors.