Recursive Factorial Function in BASH Programming

in #programming5 years ago

As you may know, the famous factorial can be done in Recursion via:

f(n) = n * f(n-1) where  f(0) = f(1) = 1

BASH supports function declaration and recursion - just like other modern programming language. See below the Recursive function to compute the factorial values.

#!/bin/bash

function f() {
    local n=$1
    if [[ $n -eq 0 ]]; then
        echo 1
    else
        echo $((n*$(f $n-1)))
    fi
}

for i in {1..10}; do
    echo "$i!=$(f $i)"
done

This BASH script prints the first 10 factorial numbers:

1!=1
2!=2
3!=6
4!=24
5!=120
6!=720
7!=5040
8!=40320
9!=362880
10!=3628800

We use "local" to keep the variables at scope of function, and we can use $() to call a function recursively.

See also: Teaching Kids Programming – Recursion in Five Minutes

Reposted to Blog

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

Important Update of Delegation Service!

  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Sort:  

hello, sir @justyy plz fix the voting bot. Every day I need to contact you to get upvote. It's already 40 minutes but my today's post gets no upvote.

my post: https://steemit.com/hive-129948/@rme/php-half-dozones-string-operations-in-php

thank you :D

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.084
BTC 60162.63
ETH 1576.76
USDT 1.00
SBD 0.42