-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpascal.sh
More file actions
48 lines (42 loc) · 1.03 KB
/
pascal.sh
File metadata and controls
48 lines (42 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/bin/bash
# Function to calculate factorial of a number
factorial() {
if [ $1 -le 1 ]; then
echo 1
else
echo $(( $1 * $(factorial $(( $1 - 1 ))) ))
fi
}
# Function to calculate binomial coefficient (nCr)
binomial_coefficient() {
n=$1
r=$2
numerator=$(factorial $n)
denominator=$(( $(factorial $r) * $(factorial $(( n - r ))) ))
echo $(( numerator / denominator ))
}
# Function to generate Pascal's Triangle
pascals_triangle() {
rows=$1
for (( i=0; i<rows; i++ ))
do
# Print leading spaces for proper alignment
for (( j=0; j<rows-i; j++ ))
do
echo -n " "
done
# Print the numbers in Pascal's Triangle
for (( j=0; j<=i; j++ ))
do
echo -n "$(binomial_coefficient $i $j) "
done
echo
done
}
# Check if the number of rows is provided as an argument
if [ -z "$1" ]; then
echo "Please provide the number of rows as an argument."
exit 1
fi
# Generate Pascal's Triangle
pascals_triangle $1