Debian Codegraph @

fibo.sh

raw symbols SCIP
1 #!/bin/bash
2 # fibo.sh : Fibonacci sequence (recursive)
3 # Author: M. Cooper
4 # License: GPL3
5
6 # ----------algorithm--------------
7 # Fibo(0) = 0
8 # Fibo(1) = 1
9 # else
10 # Fibo(j) = Fibo(j-1) + Fibo(j-2)
11 # ---------------------------------
12
13 MAXTERM=15 # Number of terms (+1) to generate.
14 MINIDX=2 # If idx is less than 2, then Fibo(idx) = idx.
15
16 Fibonacci ()
17 {
18 idx=$1 # Doesn't need to be local. Why not?
19 if [ "$idx" -lt "$MINIDX" ]
20 then
21 echo "$idx" # First two terms are 0 1 ... see above.
22 else
23 (( --idx )) # j-1
24 term1=$( Fibonacci $idx ) # Fibo(j-1)
25
26 (( --idx )) # j-2
27 term2=$( Fibonacci $idx ) # Fibo(j-2)
28
29 echo $(( term1 + term2 ))
30 fi
31 # An ugly, ugly kludge.
32 # The more elegant implementation of recursive fibo in C
33 #+ is a straightforward translation of the algorithm in lines 7 - 10.
34 }
35
36 for i in $(seq 0 $MAXTERM)
37 do # Calculate $MAXTERM+1 terms.
38 FIBO=$(Fibonacci $i)
39 echo -n "$FIBO "
40 done
41 # 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
42 # Takes a while, doesn't it? Recursion in a script is slow.
43
44 echo
45
46 exit 0