ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Bash Factorial Calculation

Bash

Goal -- WPM

Ready
Exercise Algorithm Area
1function factorial() {
2local n=$1
3local result=1
4
5# Handle negative input edge case
6if [ "$n" -lt 0 ]; then
7echo "Factorial is not defined for negative numbers."
8return 1
9fi
10
11# Handle base case for 0!
12if [ "$n" -eq 0 ]; then
13echo 1
14return 0
15fi
16
17# Calculate factorial using a loop
18for (( i=1; i<=n; i++ )); do
19result=$((result * i))
20done
21
22echo "$result"
23}
24
25# Example usage:
26# factorial 5
Algorithm description viewbox

Bash Factorial Calculation

Algorithm description:

This Bash script calculates the factorial of a non-negative integer. The factorial of a number n (denoted as n!) is the product of all positive integers less than or equal to n. This is a fundamental mathematical operation with applications in combinatorics, probability, and computer science algorithms.

Algorithm explanation:

The `factorial` function takes an integer `n` as input. It initializes `result` to 1. It first checks for invalid input: if `n` is negative, it prints an error message and returns 1. If `n` is 0, it returns 1, as 0! is defined as 1. For positive `n`, it uses a `for` loop that iterates from 1 up to `n`. In each iteration, `result` is multiplied by the current loop variable `i`. The time complexity is O(n) because the loop runs `n` times. The space complexity is O(1) as it only uses a few variables. The correctness is ensured by the iterative multiplication of all integers from 1 to `n`.

Pseudocode:

function factorial(n):
  if n < 0:
    print error message
    return 1
  if n == 0:
    return 1
  initialize result to 1
  loop from i = 1 to n:
    result = result * i
  return result