Write a program to print the following pattern:
1
1 1
1 2 1
1 3 3 1
Objective
Write a Java program to print Pascal's Triangle using the factorial formula.
Algorithm / Approach
- Create a helper method
fact(x)to calculate the factorial of a number. - In the
show()method, use an outer loop (i) from 0 to 5 for rows. - Print leading spaces to format it as a pyramid.
- Use an inner loop (
c) from 0 toifor columns. - Calculate the value at that position using the combination formula:
i! / (c! * (i - c)!). - Print the value and a newline.
Test.java
class Test {
int fact(int x) {
int res = 1;
for(int i = 1; i < x; i++) {
res = res*i;
}
return res;
}
void show() {
int y;
for(int i=0; i<=5; i++) {
for(int c = 0; c<=(5-i-2); c++) {
System.out.print(" ");
}
for(int c =0; c<= i; c++) {
y =fact(i)/(fact(c)*fact(i-c));
System.out.print(y+" ");
}
System.out.println();
}
}
public static void main(String[] a)
{
Test t = new Test();
t.show();
}
}
Explanation of the Program
- Pascal's Triangle is a mathematical triangular array of binomial coefficients.
- The value at any position (row
i, columnc) can be calculated mathematically using combinations (nCr). - The formula for nCr is
n! / (r! * (n - r)!). The program delegates the factorial calculation to a separate helper method to keep the main logic clean.
Complexity
Time Complexity
O(n3) - Due to calculating the factorial repeatedly for every cell.
Space Complexity
O(1)