How do you find the factorial of a number in a Bash script?

前端 未结 13 2093
别那么骄傲
别那么骄傲 2021-02-14 03:24

In shell scripting how to find factorial of a number?

相关标签:
13条回答
  • 2021-02-14 03:48
    #!/bin/bash
    counter=$1 #first argument
    factorial=1
    while [ $counter -gt 0 ] #while counter > 0
    do
       factorial=$(( $factorial * $counter ))
       counter=$(( $counter - 1 ))
    done
    echo $factorial
    
    0 讨论(0)
  • 2021-02-14 03:50

    I almost completely agree with Vitalii Fedorenko, I would just like paxdiablo suggests use bc, here's the code from Vitalii Fedorenko but modified to use bc.

    #!/bin/bash
    counter=$1
    output=1
    while [ $counter -gt 1 ] #while counter > 1 (x*1=x)
    do
            output=$(echo "$output * $counter" | bc)
            counter=$(($counter - 1))
    done
    #remove newlines and '\' from output
    output=$(echo "$output" | tr -d '\' | tr -d '\n')
    echo "$output"
    exit
    

    This method is better because bc allows you to use strings, instead of integers, making it possible for you to calculate much bigger numbers.

    I apologize if I haven't used tr correctly, I am not very familiar with it.

    0 讨论(0)
  • 2021-02-14 03:57

    Please use this script to find factorial in Bash,

    #!/bin/bash
    
    num=$1
    fact=1
    for((i=1; i<=$num; i++))
    do
            let fact=fact*i
    done
    
    echo "Factorial is $fact"
    
    0 讨论(0)
  • 2021-02-14 04:03

    You can use:

    seq -s "*" 1 10 | sed 's/*$//g' |bc
    

    on a mac

    0 讨论(0)
  • 2021-02-14 04:04
    echo 500 | dc -e '?[q]sQ[d1=Qd1-lFx*]dsFxp'
    
    0 讨论(0)
  • 2021-02-14 04:04

    There are a number of instructive examples on Rosetta Code.

    Here's one I found particularly useful:

    function factorial {
      typeset n=$1
      (( n < 2 )) && echo 1 && return
      echo $(( n * $(factorial $((n-1))) ))
    }
    
    0 讨论(0)
提交回复
热议问题