Question

I just asked another question about pascal triangle about finding sum of 1500th row. I'm so glad that people answered so quickly, But unfortunately later i realized, i need each individual number on 1500th row.

Here i found an easy way to calculate any number on pascal triangle but when i try to use formula in my code, program crashes in start.

#include"stdio.h"
int factorial(int);

int main()
{
    int i=0;
    for(i=0; i<1501; i++)
    {
       printf("%d \n" , (factorial(1500)/factorial(1500-i))/factorial(i) );
    }
}
int factorial(int x)
{
    if(x<2)
    return 1;
    else
    {
        return x*factorial(x-1);
    }
}
Was it helpful?

Solution

You need a biginteger library for the results, since

binom(1500,750) = 722462892448930217028116073228485295944376343040546523665632913653613596406381727723198055046187955623124069093412562720869577867557610868874271130828359513282184417776042792372322074253393127328396528996120053749558122610911178218582669317535346728464707661495135518682519172221470420360910320792434869988224466647627642393919250205687942318888922893189087379790541907686956429837978631252775258630376332505697937034877619012586751274240109457111424

exceeds even the usual double range.

But with such a type available, the relation

binom(n,k+1) = binom(n,k)*(n-k)/(k+1)

allows a simple, relatively efficient implementation:

bigint value = 1;
int numerator = 1500 + 1, denominator = 0;
for(; denominator <= 1500; --numerator, ++denominator, value = value*numerator/denominator)
{
    output(value);
}

where output is whatever output method the library provides.

The value = value*numerator/denominator part needs to be adapted if the library doesn't offer overloads for multiplying/dividing bigintegers and normal ints.

OTHER TIPS

Use a linear algorithm for the factorial instead, to not stack overflow through recursion:

int factorial(int x) {
    if (x < 2) return 1;

    int result = x;

    while (--x) {
        result *= x;
    }

    return result;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top