Bash Script - Fibonacci

后端 未结 6 1650
日久生厌
日久生厌 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:22

    There are a couple of issues with your code. You cannot use $? for any useful arithmetic because the number wraps around at 255. And the embedded $((...)) is not useful at all -- you are already in arithmetic context inside the double parentheses.

    #!/bin/bash
    
    fib()
    {
      local number term1 term2 # Avoid leaking to main scope
      number=$1
      if ((number < 2))
        then
          ((tmp=number))
      else
          ((--number))
          term1=$(fib "$number")
          ((--number))
          term2=$(fib "$number")
          ((tmp=term1+term2))
      fi
      ((result=result+tmp))
      printf '%s\n' "$result"
    }
    
    #Main Program.
    fib "$1"   # Quote argument properly!
    

    Inside the (( arithmetic parentheses )) you don't need the $ in front of variables; it's harmless, but you should probably try to be consistent.

    As with any naïve Fibonacci implementation, this is hugely inefficient. It would be smarter to calculate the head of the sequence once in a helper function, then pull the final result and display it.

    #!/bin/bash
    
    fib2() {
        local f
        ((f=$1+$2))
        printf '%i %i\n' "$f" "$1"
    }
    
    fib()
    {
        local i j
        j=$1
        shift
        for((i=1; i

提交回复
热议问题