-2

Is it possible to write a script that calculates the nth Fibonacci number - iteratively. I did it recursive (showed below) but could find solution iteratively. Please help.

#!/bin/bash
fib()
{
  if [ $1 -le 0 ]
  then
    echo 0
    return 0
  fi
  if [ $1 -le 2 ]
  then
    echo 1
  else
    a=$(fib $[$1-1])
    b=$(fib $[$1-2])
    echo $(($a+$b))
  fi
}
jww
  • 97,681
  • 90
  • 411
  • 885
axel_87
  • 37
  • 6

2 Answers2

0

I'm not into bash and had no possibility to check but it should be something like:

fib()
{
  if [ $1 -le 0 ]
  then
    echo 0
    return 0
  fi
  if [ $1 -le 2 ]
  then
    echo 1
  else
    a = 1
    b = 1
    for i in {2..$1}
    do
      c = $b;
      b = $a + $b;
      a = $c
    done
    echo $($b)
  fi
}

(there might be some errors in spelling)

for java it would work like:

public int fib(n){
    if(n <= 1) {
        return n;
    }
    int fib = 1;
    int prevFib = 1;

    for(int i=2; i<n; i++) {
        int temp = fib;
        fib+= prevFib;
        prevFib = temp;
    }
    return fib;
}
Brokkoli 71
  • 141
  • 9
0

Here's the iterative approach:

function fib() {
  local n=$1
  local x=0
  local prev1=0
  local prev2=0
  local cur=0
  for (( x = 1 ; x <= n ; x++ ))
  do
    if [[ $x == 1 || $x == 2 ]] ;  then
      prev1=1
      prev2=1
      cur=1
      continue
    fi
    cur=$(( prev1 + prev2 ))
    prev2=$prev1
    prev1=$cur
  done
  echo $cur
}
Mark
  • 4,249
  • 1
  • 18
  • 27