0

I have been given the following problem:

Given an integer rowIndex, return the rowIndex row of the Pascal's triangle. Notice that the row index starts from 0.

Pascal Triangle elements can be predicted with the function: n! / k!(n-k)!

My below code works for most entries except a few and I can't figure out where I am going wrong.

For example if I enter 24 all the entries are correct excpet for the second element and second to last element.

I get [1,23, ...... 23, 1] when i should get [1,24, ...... 24, 1];

Assuming the math function is correct, 99.99% sure it is, what am I missing here?

double factorial(double n);
int* getRow(int rowIndex, int* returnSize){
    
    *returnSize = rowIndex + 1;
    int* ans = malloc(*returnSize * sizeof(int));

    double a = factorial(rowIndex);
    for(int i = 0; i<=rowIndex; i++) {
         ans[i] = a / ( factorial(i) * factorial(rowIndex-i) );
    }
    
    return ans;
}

double factorial(double n) {
    double fact=1;
    for (int i = 1; i <= n; ++i) {
            fact *= i;
    }         
    return fact;
}
seamus
  • 2,681
  • 7
  • 26
  • 49
  • 1
    You are missing the fact that factorial overflows the bit storage available, and possibly that `double` does not sit well with what should be calculations with integers. – Weather Vane Jan 03 '21 at 19:20
  • 1
    [`24!`](https://www.wolframalpha.com/input/?i=24%21) has `20` significant decimal digits, which is more than the usual `double` type can hold. – dxiv Jan 03 '21 at 19:25

0 Answers0