2012-07-06 09:07:02Morris

[UVA][JAVA] 485 - Pascal's Triangle of Death


 Pascal's Triangle of Death 

In this problem, you are asked to generate Pascal's Triangle. Pascal's Triangle is useful in many areas from probability to polynomials to programming contests. It is a triangle of integers with ``1'' on top and down the sides. Any number in the interior equals the sum of the two numbers above it. For example, here are the first 5 rows of the triangle.

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

In ``Pascal's Triangle of Death,'' you are to generate a left justified Pascal's Triangle. When any number in the triangle is exceeds or equals 1060, your program should finish printing the current row and exit. The output should have each row of the triangle on a separate line with one space between each element.

The final element of each line should be directly followed by a newline. There is no space after the last number on each line.

Sample Input

There is no input for this problem.

Sample Output

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
.
.
.
etc.

import java.math.BigInteger;

public class Main {
    public static void main(String[] args) {
        BigInteger[][] dp = new BigInteger[300][300];
        dp[0][0] = new BigInteger("1");
        int n = 0;
        for(int i = 1; ; i++) {
            int endflag = 0;
            dp[i][0] = new BigInteger("1");
            for(int j = 1; j < i; j++) {
                dp[i][j] = dp[i-1][j].add(dp[i-1][j-1]);
                if(dp[i][j].toString().length() >= 61)
                    endflag = 1;
            }
            dp[i][i] = new BigInteger("1");
            if(endflag == 1) {
                n = i;
                break;
            }
        }
        for(int i = 0; i <= n; i++) {
            System.out.print("1");
            for(int j = 1; j <= i; j++)
                System.out.print(" " + dp[i][j].toString());
            System.out.println("");
        }
    }
}