JavaScript Program to Print Pascal’s Pattern Triangle Pyramid

Pascal’s Triangle is a mathematical concept that produces a triangular array of binomial coefficients. It is a series of numbers arranged in the shape of a pyramid, following Pascal’s Triangle pattern. Each number in the pyramid is the sum of the two numbers directly above it in the previous row, with the apex of the pyramid being 1.

Pascal’s Pattern Triangle Pyramid

Table of Content

  • Using Recursion
  • Using Binomial Coefficients

Using Recursion

This approach involves using recusrion to generate Pascal’s Pattern Triangle Pyramid using below steps.

  • Define the number of rows for the pyramid.
  • Use nested loops to iterate through each row and column.
  • Calculate the value for each position in the pyramid based on the row and column index.
  • Print each value to display the pyramid.

Example: The below code recursively prints the Pascal’s Triangle Pyramid in JavaScript.

Javascript




function printPascalsPyramid(rows) {
    for (let i = 0; i < rows; i++) {
        let output = '';
        for (let j = 0; j <= i; j++) {
            output += pascalNumber(i, j) + ' ';
        }
        console.log(output);
    }
}
 
function pascalNumber(row, column) {
    if (column === 0 || column === row) {
        return 1;
    } else {
        return pascalNumber(row - 1, column - 1) +
            pascalNumber(row - 1, column);
    }
}
 
printPascalsPyramid(5);


Output

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

Time complexity: O(2^n), where n is the number of rows in the pyramid.

Space complexity: O(n)

Using Binomial Coefficients

Another approach involves using the binomial coefficients formula to generate Pascal’s Pattern Triangle Pyramid.

  • Define the number of rows for the pyramid.
  • Use the binomial coefficient formula to calculate the value for each position in the pyramid.
  • Print each value to display the pyramid

Example: The below code prints Pascal’s Triangle using binomial coefficients in JavaScript.

Javascript




function printPascalsPyramid(rows) {
    for (let i = 0; i < rows; i++) {
        let output = '';
        for (let j = 0; j <= i; j++) {
            output += binomialCoefficient(i, j) + ' ';
        }
        console.log(output);
    }
}
 
function binomialCoefficient(n, k) {
    let res = 1;
    if (k > n - k) {
        k = n - k;
    }
    for (let i = 0; i < k; ++i) {
        res *= (n - i);
        res /= (i + 1);
    }
    return res;
}
 
printPascalsPyramid(5);


Output

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

Time complexity: O(n^3), where n is the number of rows.

Space complexity: O(1)