Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pascal's Triangle Format [duplicate]

The assignment is to create Pascal's Triangle without using arrays. I have the method that produces the values for the triangle below. The method accepts an integer for the maximum number of rows the user wants printed.

public static void triangle(int maxRows) {
    int r, num;
    for (int i = 0; i <= maxRows; i++) {
        num = 1;
        r = i + 1;
        for (int col = 0; col <= i; col++) {
            if (col > 0) {
                num = num * (r - col) / col;    
            }
            System.out.print(num + " ");
        }
        System.out.println();
    }
}

I need to format the values of the triangle such that it looks like a triangle:

              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

I can't for the life of me figure out how to do that. Please answer keeping in mind that I'm a beginner in Java programming.

like image 818
Sidarth Shahri Avatar asked Nov 12 '13 00:11

Sidarth Shahri


People also ask

How is Pascal's Triangle symmetrical?

Each row of Pascal's triangle is symmetric. (nr)=(nn−r), since choosing r objects from n objects leaves n−r objects, and choosing n−r objects leaves r objects. This means that the coefficient of xr in the expansion of (1+x)n is the same as the coefficient of xn−r.

Is Pascal's triangle always the same?

Pascal's triangle is a never-ending equilateral triangle of numbers that follow a rule of adding the two numbers above to get the number below. Two of the sides are “all 1's” and because the triangle is infinite, there is no “bottom side.”


1 Answers

public static long pascalTriangle(int r, int k) {
    if (r == 1 || k <= 1 || k >= r) return 1L;
    return pascalTriangle(r - 1, k - 1) + pascalTriangle(r - 1, k);
}

This method allows you to find the k-th value of r-th row.

like image 188
Boa Hancock Avatar answered Sep 23 '22 12:09

Boa Hancock