Search code examples
ccombinationsfactorialpascals-triangle

Pascal's triangle in C with combinations


#include <stdio.h>
long factorial(int num)
{
    int counter;
    int fact = 1;
    for (counter = num; counter > 0; counter--) fact *= counter;
    return fact;
}

float combinations(int n, int k)
{
    int numerator = factorial(n);
    int denominator = factorial(k) * factorial(n-k);
    float fraction = numerator/denominator;
    return fraction;
}
int main()
{
    printf("How many rows of Pascal\'s triangle should I print?\t");
    int rows = GetInteger();
    int counter;
    int counter2;
    for (counter = 1; counter <= rows; counter++)
    {
        int y = rows-counter;
        for (; y > 0; y--) printf("   ");
        for (counter2 = 0; counter2 <= counter; counter2++)
                printf("%6.0lu", (long) combinations(counter, counter2));
        printf("\n");
    }
}

Every time I go past twelve rows, the numbers start to decrease. What am i doing wrong?

And, GetInteger() is just a scanf() with a few touch ups. I am 100% sure it works perfectly.


Solution

  • After 12th row factorial and so pascal triangle elements become too large so int type cannot hold them - so you get overflow (most probably values you get are wrapped around maximum int value).

    P.S. why do you use 3 different types in your code (long, int, float)? As k!*(n-k)! always divides n! you do not need float value (you use integer division and cast result to long anyway). Just use the biggest integer type you can, or some custom BigInt type that can hold integer numbers of arbitrary length - so you can show correct values for large row numbers.