Recursive function in bash

后端 未结 6 1649
渐次进展
渐次进展 2020-12-13 09:33

I want to do a function that will return the factorial of a number in bash

Here\'s the current code that doesn\'t work, can anyone tell me what\'s wrong and how to c

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 10:12

    #!/bin/bash
    
    function factorial() 
    { 
       if (( $1 < 2 ))
       then
         echo 1
       else
         echo $(( $1 * $(factorial $(( $1 - 1 ))) ))
       fi
    }
    

    This will work better.

    (It works up to 25, anyway, which should be enough to prove the point about recursion.)

    For higher numbers, bc would be the tool to use, making the ninth line above:

    echo "$1 * $(factorial $(( $1 - 1 )))" | bc
    

    but you have to be a bit careful with bc --

    $ factorial 260
    38301958608361692351174979856044918752795567523090969601913008174806\
    51475135399533485285838275429773913773383359294010103333339344249624\
    06009974551133984962615380298039823284896547262282019684886083204957\
    95233137023276627601257325925519566220247124751398891221069403193240\
    41688318583612166708334763727216738353107304842707002261430265483385\
    20637683911007815690066342722080690052836580858013635214371395680329\
    58941156051513954932674117091883540235576934400000000000000000000000\
    00000000000000000000000000000000000000000
    

    was quite a strain on my poor system!

提交回复
热议问题