Pascal
Pascal
Example:
Input: N = 5
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Method 1: Using nCr formula i.e. n!/(n-r)!r!
0C0
1C0 1C1
2C0 2C1 2C2
3C0 3C1 3C2 3C3
Algorithm:
filter_none
edit
play_arrow
brightness_4
# Print Pascal's Triangle in Java
from math import factorial
# input n
n = 5
for i in range(n):
for j in range(n-i+1):
for j in range(i+1):
# nCr = n!/((n-r)!*r!)
print(factorial(i)//(factorial(j)*factorial(i-j)), end=" ")
Method 2: We can optimize the above code by the following concept of a Binomial
Coefficient, the i’th entry in a line number line is Binomial Coefficient C(line,
i) and all lines start with value 1. The idea is to calculate C(line, i) using
C(line, i-1).
filter_none
edit
play_arrow
brightness_4
# Print Pascal's Triangle in Java
# input n
n = 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Time complexity: O(N2)
Method 3: This is the most optimized approach to print Pascal’s triangle, this
approach is based on powers of 11.
11**0 = 1
11**1 = 11
11**2 = 121
11**3 = 1331
Implementation:
filter_none
edit
play_arrow
brightness_4
# Print Pascal's Triangle in Python
# input n
n = 5
# iterarte upto n
for i in range(n):
# adjust space
print(' '*(n-i), end='')
# compute power of 11
print(' '.join(map(str, str(11**i))))
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1