ISourceCode

Make the frequent cases fast and the rare case correct

Binomial Coefficient and Pascal Triangle

The coefficients that appear in the binomial expansion are called binomial coefficients.

Binomial coefficients can be recursively defined as follows:

C(n, 0) = C(n, n) = 1 for all n > 0;
C(n, k) = C(n -1, k -1) + C(n – 1, k) for all 0 < k < n.

Arranging binomial coefficients into rows for successive values of n, and in which k ranges from 0 to n, gives a triangular array called Pascal's triangle – Wikipedia .

Algorithm:

algorithm Binomial(n, k)
// Computes C(n, k) using dynamic programming
// Input: Integers n ≥ k ≥ 0
// Output: The value of C(n, k)
for i ← 0 to n do
  for j ← 0 to min(i, k) do
    if j = 0 or j = i then
       A[i, j] ← 1
    else A[i, j] ← A[i − 1, j − 1] + A[i − 1, j]
return A[n, k]

Implementation:

public class pascal {

        public static void main(String [] args)
        {

                int [][] pascal = new int[8][];

                for (int i=0; i<pascal.length; i++)
                {
                        pascal[i] = new int[i+1];
                        pascal[i][0] = 1;
                        pascal[i][i] = 1;
                        for (int j=1; j<i; j++)
                        {
                                pascal[i][j] = pascal[i-1][j]+pascal[i-1][j-1];
                        }
                }

                for (int i=0; i<pascal.length; i++)
                {

                        for (int j=0; j<pascal[i].length; j++)
                        {
                                System.out.print(" "+pascal[i][j]);
                        }

                        System.out.println("");
                }
        }

}

> java pascal
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: