-2
row 1 |     1
row 2 |    1 1   
row 3 |   1 2 1
row 4 |  1 3 3 1
row 5 | 1 4 6 4 1

I recently made a computer program that involved Pascal's Triangles.

However I got obsessed with optimizing it.

I know there is a way to get Nth row / Xth element of the triangle. However any formulas I tried (including from math stack exchange) did not worked.

What I want is for example to have 5th row, 2nd element and result to be 4.

Because most of other similar answers did not really work, will be glad, if you give me the answer as a function in some programming language.
Let suppose we have function long factorial(long x) already done.

Thanks.

References that does not work:

Nick
  • 99
  • 3
  • ${N-1} \choose {X-1}$ will work because generally it is $N \choose X$ where $N$ starts from $0$ and $X$ takes values from $0$ to $N$ but your desired index starts from $1$ instead of $0$. – Infinity_hunter Aug 16 '21 at 12:50
  • can you write it as formula with factorial ! . also let me know what index is from 0 and what from 1 – Nick Aug 16 '21 at 12:54
  • 1
    You can look here for the definition. What I am saying is if you reindex your rows from $0$ to $4$ or start counting from $0$ then the $x$ th ($x$ starts from $0$) element in $n$ th row is $n \choose x$ – Infinity_hunter Aug 16 '21 at 12:57
  • Works like a charm. Thanks. I suppose other example add / subtracts 1's. – Nick Aug 16 '21 at 13:14

1 Answers1

0

With help from @Infinity_hunter and Wikipedia (https://en.wikipedia.org/wiki/Binomial_coefficient)

Example is in C++ but can be rewritten in C, Java, PHP, nodejs very easy:

#include <cstdio>

long factoriel(int x){ long result = 1;

if (x == 0 || x == 1)
    return result;

for(int i = 2; i &lt;= x; ++i)
    result = result * i;

return result;

}

long pascal_triangle_nth(int row, int x){ --row; --x;

return factoriel(row) / ( factoriel(row - x) * factoriel(x) );

}

int main(){ for(int i = 1; i <= 9; ++i){ printf("%d >>>> ", i);

    for(int j = 1; j &lt;= i; ++j)
        printf(&quot; %ld &quot;, pascal_triangle_nth(i, j));

    printf(&quot;\n&quot;);
}

}

Result:

1 >>>>  1 
2 >>>>  1  1 
3 >>>>  1  2  1 
4 >>>>  1  3  3  1 
5 >>>>  1  4  6  4  1 
6 >>>>  1  5  10  10  5  1 
7 >>>>  1  6  15  20  15  6  1 
8 >>>>  1  7  21  35  35  21  7  1 
9 >>>>  1  8  28  56  70  56  28  8  1 
Nick
  • 99
  • 3