Open In App

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

Using Recursion

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

Example: The below code recursively prints the Pascal’s Triangle Pyramid in 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.

Example: The below code prints Pascal’s Triangle using binomial coefficients in 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)


Article Tags :