Bash Factorial Calculation
#!/bin/bash # Function to calculate factorial calculate_factorial() { local n="$1" local result=1 # Base case: factorial of 0 is 1 if [ "$n" -eq 0 ]; then echo "1" return fi # Calculate factorial using a loop for (( i=1; i<=n; i++ )); do result=$((result * i)) done echo "$result"...
This Bash script defines a function `calculate_factorial` that computes the factorial of a given non-negative integer. The factorial of a non-negative integer n is the product of all positive integers less than or equal...
The `calculate_factorial` function computes n! (n factorial). It initializes `result` to 1. The base case, where `n` is 0, is handled by returning 1, as 0! is defined as 1. For positive integers, a `for` loop iterates from 1 up to `n`. In each iteration, `result` is multiplied by the current loop variable `i`. This process accumulates the product of all numbers from 1 to `n`. The time complexity is O(n) because the loop runs `n` times. The space complexity is O(1) as it uses a constant amount of extra space for variables. The loop boundaries are essential for correct calculation, ensuring all numbers from 1 to `n` are included in the product.
function calculate_factorial(n): if n is 0: return 1 result = 1 for i from 1 to n: result = result * i return result