This is the syntax highlighted version of BinomialTheorem.java.
/*************************************************************************
* Compilation: javac BinomialTheorem.java
* Execution: java BinomialTheorem N
*
* Prints out (x+y)^N for positive integer N using the Binomial Theorem
* and Pascal's triangle.
*
* % java BinomialTheorem 5
* 1 5 10 10 5 1
*
* % java BinomialTheorem 10
* 1 10 45 120 210 252 210 120 45 10 1
*
*************************************************************************/
public class BinomialTheorem {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
int[] a = new int[N+1];
int[] aold = new int[N+1];
// initialize a[0] = 1, a[i] = 0 for i > 0
a[0] = 1;
for (int i = 0; i < N; i++) {
// copy current values
for (int j = 0; j <= N; j++)
aold[j] = a[j];
// update new values
for (int j = 1; j <= N; j++)
a[j] = aold[j] + aold[j-1];
}
// print results
for (int i = 0; i <= N; i++)
System.out.print(a[i] + " ");
System.out.println();
}
}
Last updated: Wed Feb 11 18:16:34 EST 2004
.
Copyright © 2004, Robert Sedgewick and Kevin Wayne.