ℹ️ 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
1#!/bin/bash
2
3# Function to calculate factorial
4calculate_factorial() {
5local n="$1"
6local result=1
7
8# Base case: factorial of 0 is 1
9if [ "$n" -eq 0 ]; then
10echo "1"
11return
12fi
13
14# Calculate factorial using a loop
15for (( i=1; i<=n; i++ )); do
16result=$((result * i))
17done
18
19echo "$result"
20}
21
22# Example usage:
23# num=5
24# fact=$(calculate_factorial "$num")
25# echo "Factorial of $num is $fact"
Algorithm description viewbox

Bash Factorial Calculation

Algorithm description:

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 to n. This is a classic mathematical function with applications in combinatorics and probability.

Algorithm explanation:

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.

Pseudocode:

function calculate_factorial(n):
  if n is 0:
    return 1
  
  result = 1
  
  for i from 1 to n:
    result = result * i
  
  return result