Pascal Triangle Program stops responding half way through.

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.

*My OS is Windows 7, my IDE is Codeblocks*

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>

using namespace 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));
}

Last edited on
It may just be taking a very long time...how long have you waited?
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.
Last edited on
1
2
3
4
5
6
int factorial(int i)
{
    if (i <= 1)
        return 1; // factorial(0) should return 1
    return (i * factorial(i - 1));
}



You can also throw reception (see documents) and be able to handle it the way you want too.
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.
On my PC, factorial(13) was bigger than an int so I got the wrong result from the function.
You may need to guard against that.
Topic archived. No new replies allowed.