How to resolve the algorithm Factorial step by step in the UNIX Shell programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Factorial step by step in the UNIX Shell programming language

Table of Contents

Problem Statement

Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Factorial step by step in the UNIX Shell programming language

Source code in the unix programming language

factorial() {
  set -- "$1" 1
  until test "$1" -lt 2; do
    set -- "`expr "$1" - 1`" "`expr "$2" \* "$1"`"
  done
  echo "$2"
}

function factorial {
  typeset n=$1 f=1 i
  for ((i=2; i < n; i++)); do
    (( f *= i ))
  done
  echo $f
}

factorial ()
{
  if [ $1 -eq 0 ]
    then echo 1
    else echo $(($1 * $(factorial $(($1-1)) ) ))
  fi
}

function factorial {
  typeset n=$1
  (( n < 2 )) && echo 1 && return
  echo $(( n * $(factorial $((n-1))) ))
}

alias factorial eval \''set factorial_args=( \!*:q )	\\
	@ factorial_n = $factorial_args[2]		\\
	@ factorial_i = 1				\\
	while ( $factorial_n >= 2 )			\\
		@ factorial_i *= $factorial_n		\\
		@ factorial_n -= 1			\\
	end						\\
	@ $factorial_args[1] = $factorial_i		\\
'\'

factorial f 12
echo $f
# => 479001600

  

You may also check:How to resolve the algorithm Sum and product of an array step by step in the V (Vlang) programming language
You may also check:How to resolve the algorithm Evaluate binomial coefficients step by step in the PL/I programming language
You may also check:How to resolve the algorithm Zig-zag matrix step by step in the Tcl programming language
You may also check:How to resolve the algorithm Unbias a random generator step by step in the Julia programming language
You may also check:How to resolve the algorithm Intersecting number wheels step by step in the Perl programming language