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

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

In shell scripting how to find factorial of a number?

13条回答
  •  傲寒
    傲寒 (楼主)
    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.

提交回复
热议问题