Bash Script - Fibonacci

后端 未结 6 1590
日久生厌
日久生厌 2021-01-24 11:05

I was trying to make a recursive function that can calculate the Fibonacci of the enter number, by the way I got stuck on how to get the values obtained by the recursion.

<
6条回答
  •  逝去的感伤
    2021-01-24 11:23

    Re tripleee's answer: this can be done much faster still.

    I think the helper function call is really expensive. Below version calculated fib 100000 at 2.344 seconds, whereas the helper-function version did the same at 1min 28.44 seconds. Although, you only get correct fibonacci up to like fib 92, at fib 93 for me you have hit the intmax_t setting.

    fibnorec(){
        # typecheck                                                                                           
        if [[ ! "$1" =~ ^[0-9]+$ ]]
        then
            return 1
        fi
    
        # make arg into int                                                                                   
        declare -i n="$1"
    
        # Return fibonacci number at index n...                                                               
        if [[ $n -le 1 ]]
        then
            # index 0 and index 1 are numbers 0 and 1 respectively.
            printf '%s\n' $n;
        fi
        # For index 2 and up (position 3 and up)
        declare -i sum=1;
        declare -i prev=1;
        for ((i=2; i

提交回复
热议问题