Wednesday, 8 December 2010

Generating Pascal's Triangle

Blaise Pascal (AD 1623 - 1662 )


In this program, we'll be generating the below number-triangle:


Pascal's Triangle


Known as Pascal's Triangle, it's a triangular array of Binomial Coefficients named after Blaise Pascal,  a French mathematician, physicist, inventor, writer and Catholic philosopher (a Jansenist apologist, to be precise), which he described in his book Traité du triangle arithmétique of 1653.


File: PascalTriangle.java


We first write a class called BinomialCoefficient for computing the Binomial Coefficient (inclusive of the Factorial class) as:



class Factorial {
static long factorial (byte i)
{
if(i == 0 || i == 1)
return (long) 1;
else 
return (long) i * factorial((byte) (i - 1));
}
}


class BinomialCoefficient {
static long binomialCoefficient(byte n, byte r){
long binCoeff = 0;

binCoeff = (long) (Factorial.factorial(n))/
(Factorial.factorial(r) * Factorial.factorial((byte) (n - r)));

return (long) binCoeff;
}
}

Next we invoke it in the PascalTriangle class below it as:


public class PascalTriangle {

public static void main(String[] args) {
 
  byte numberOfRows = 15;
String[] sumOfBinomialCoefficients = new String[numberOfRows] ;
System.out.println();
for(byte rowIndex = 0;rowIndex < numberOfRows;rowIndex++)
{
sumOfBinomialCoefficients[rowIndex] = "";
for(byte columnIndex = 0;columnIndex <= rowIndex;columnIndex++)
{
  sumOfBinomialCoefficients[rowIndex] +=  
     BinomialCoefficient.binomialCoefficient
     (rowIndex,columnIndex) + " ";
}
}
for(byte rowIndex = 0;rowIndex < numberOfRows;rowIndex++)
{
for(long padding = 0;padding < 
      (sumOfBinomialCoefficients[numberOfRows - 1].length() -    
      sumOfBinomialCoefficients[rowIndex].length())/2;padding++)
{
System.out.print(" ");
}
for(byte columnIndex = 0;columnIndex <= rowIndex; columnIndex++)
{
System.out.print(BinomialCoefficient.binomialCoefficient
    (rowIndex,columnIndex) + " ");
}
System.out.println();
}
}

}


A little note first: I pasted the program written in Eclipse IDE in a notepad and saved it inside the Java Programs folder in drive C:\. I'll be running the program in the Command-Line Interface

Here, I've displayed the triangle upto 15 rows. If you want more number of rows, just assign it to the numberOfRows variable. The output is as:


2 comments:

  1. Dennis, thanks for the great program. There is a small error in your program. Once I corrected it, I was getting the right results.
    Here is the error:
    binCoeff = (long) (Factorial.factorial(n)/
    Factorial.factorial(r) * Factorial.factorial((byte) (n - r))));
    ------
    It needed to be:
    binCoeff = (long) (Factorial.factorial(n))/
    (Factorial.factorial(r) * Factorial.factorial((byte) (n - r)));
    and it worked fine. Thanks very much.

    ReplyDelete
  2. Hi Ilango, thanks for the feedback. Sorry I didn't check my blog for a long long time.

    ReplyDelete