Issue in getting row of Pascal triangle due to double precision

114 views Asked by At

I am try to get a list of integer containing all the numbers in a particular row in Pascal triangle. I am having issue because of the double precision.

Following is the code

public List<int> GetRow(int rowIndex)
{
    List<int> l = new List<int>();

    l.Add(1);
    for(int i=1;i<=rowIndex;i++)
    {
        int nextNum = (int)( ((rowIndex + 1 - i)/(double)i)  * l[i-1]);
        l.Add(nextNum);
    }

    return l;
}

I ran it for 11th row and the result I am getting is

{1, 11, 55, 165, 330, 461, 461, 329, 164, 54, 10, 0}

but the expected is

{1, 11, 55, 165, 330, 462, 462, 330, 165, 55, 11, 1}

How can I solve the issue.

P.S: I am using Mono

1

There are 1 answers

2
Taukita On BEST ANSWER

(int) truncate double number before conversion.

Try this code instead

public static List<int> GetRow(int rowIndex)
{
    List<int> l = new List<int>();

    l.Add(1);
    for (int i = 1; i <= rowIndex; i++)
    {
        int nextNum = (int)Math.Round(((rowIndex + 1 - i) / (double)i) * l[i - 1]);
        l.Add(nextNum);
    }

    return l;
}