Shell script to generate Fibonacci series using recursion


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Shell script to generate Fibonacci series using recursion
# 8  
Old 12-08-2009
Yes, the recursive approach is not the most efficient way. What is also interesting is the difference between shells. I changed your code yet again a bit so that it would work in any posix shell:

Code:
Fibonacci (){
  case $1 in
    0|1) printf "$1 " ;;
    *)   printf "$(( $(Fibonacci $(($1-2))) + $(Fibonacci $(($1-1))) )) ";;
  esac
}

i=0
while [ $i -lt $1 ]
do
  i=$((i+1))
  Fibonacci $i
done
echo


I tested it with bash zsh, dash and ksh:
Code:
$ time ./testzsh 10
1 1 2 3 5 8 13 21 34 55

real    0m0.837s
user    0m0.180s
sys     0m0.648s
$ time ./testbash 10
1 1 2 3 5 8 13 21 34 55

real    0m0.887s
user    0m0.300s
sys     0m0.580s
$ time ./testdash 10
1 1 2 3 5 8 13 21 34 55

real    0m0.292s
user    0m0.048s
sys     0m0.240s
$ time ./testksh 10
1 1 2 3 5 8 13 21 34 55

real    0m0.092s
user    0m0.088s
sys     0m0.000s

As is my usual experience, ksh is quite a bit faster then other shells.

I also tested a nonrecursive version (timed in ksh):
Code:
$ time ./nonrecurs 10
0 1 1 2 3 5 8 13 21 34 55

real    0m0.013s
user    0m0.016s
sys     0m0.000s

And the difference will become vast once the number goes to 20 and higher.

Last edited by Scrutinizer; 12-08-2009 at 10:23 PM..
# 9  
Old 12-09-2009
I found this one on my notes Smilie
Code:
#!/bin/sh
fibonnacci()
{
        case $n in
                0) echo 0;      return;;
                1) echo 0 1;    return;;
                *) echo -n 0 1
                                a=0; b=1; c=2;
                                while [ $c -le $n ]
                                do
                                        t=$(( a + b ))
                                        echo -n " $t"
                                        a=$b; b=$t;
                                        c=$(( c + 1 ))
                                done
                                echo
                                return;;
        esac
}
#
n=${1:-10}
if [ ! `expr $n + 1 2> /dev/null` ] ; then
        echo "Value of the arguments < $n > IS NOT an integer!"
        exit 1
fi
echo "Fibonnacci series for value $n is:"
fibonnacci $n
exit 0

# 10  
Old 12-09-2009
Computing Fibonacci series via recursion is (because each new element n needs two passes of the algorithm, one for n-1 and one for n-2) not the best idea, to put it mildly. It is easy to show that the Landau-symbol for the runtime characteristics of this algorithm is:

Image

(Basically it means that the time necessary to compute some x will be doubled when x increases by 1.)

The main difference between the original and the improved version was:

Code:
x=`expr $x - 1`

and

Code:
(( x = x - 1 ))

The reason for this is the fact that "expr" is an external program the shell has to call via the "fork()" system call, which is time intensive. The second variant is completely internal and doesn't need to call an external program so this overhead is removed. The Landau-symbol for the runtime characteristics is still the same as above.

The most efficient implementation is non-recursive and probably something like:

Code:
#!/bin/ksh

fibonacci ()
{
typeset -i iStopAt=$1
typeset -i iFibLast1=1
typeset -i iFibLast2=0
typeset -i iFibCurrent=1
typeset -i iCurrIndex=1

while [ $iCurrIndex -le $iStopAt ] ; do
     (( iFibCurrent = iFibLast1 + iFibLast2 ))
     iFibLast2=iFibLast1
     iFibLast1=iFibCurrent
     (( iCurrIndex += 1 ))
done

print - "$iFibCurrent"
return 0
}

# main ()
iCnt=1

while [ iCnt -le 25 ] ; do
     fibonacci $iCnt
     (( iCnt += 1 ))
done
exit 0

I hope this helps.

bakunin
# 11  
Old 12-09-2009
I made the following non-recursive alternative to use with the tests:

Code:
#!/bin/ksh

Fibonacci (){
  for (( i=0; i<=$1; i++ )); do
    case $i in
      0|1) val=$i ;;
      *)   val=$((val1 + val2));;
    esac
    printf "$val "
    val2=$val1
    val1=$val
  done
}

Fibonacci $1
echo


Last edited by Scrutinizer; 12-09-2009 at 03:01 PM..
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

Shell script newbie- how to generate service log from shell script

Hi, I am totally a newbie to any programming languages and I just started an entry level job in an IT company. One of my recent tasks is to create a script that is able to show the log file of linux service (i.e. ntpd service) lets say, if I run my script ./test.sh, the output should be... (3 Replies)
Discussion started by: xiaogeji
3 Replies

2. Shell Programming and Scripting

Generate documentation for a shell script

Hi, I've written a shell script with proper intentation and commenting structure. However, I would like to generate documentation for the shell which I have written. Is there any tool as such to generate it like we have javagen/docgen ? Please help. Thanks, Arjun (0 Replies)
Discussion started by: arjun_arippa
0 Replies

3. Shell Programming and Scripting

Fibonacci series -going into infinite loop

Hello, I am a beginner to shell programming. Coded the following for Fibonacci series. #!/bin/bash fib() { i=0 j=1 arr=0 arr=1 echo "enter the limit:" read n while do fo= expr $j - 1 f1=$j f2= expr $j + 1 arr= expr ${arr} + ${arr} echo ${arr} (3 Replies)
Discussion started by: Rookie222
3 Replies

4. Shell Programming and Scripting

generate logfile in a shell script

Unix Gurus, I have a shell script which has few "echo" statements. I am trying to create a logfile where all the outputs of the echo statement sare stored. I will have to add this as the final step in the existing script so that everytime the script runs, a logfile is generated with all the... (1 Reply)
Discussion started by: shankar1dada
1 Replies

5. Homework & Coursework Questions

Help with shell script to find sum of first n numbers of Fibonacci series

Use and complete the template provided. The entire template must be completed. If you don't, your post may be deleted! 1. The problem statement, all variables and given/known data: Shell script to find sum of first n numbers of Fibonacci series 2. Relevant commands, code, scripts,... (0 Replies)
Discussion started by: Kshitija
0 Replies

6. Shell Programming and Scripting

Shell script to find the sum of first n Fibonacci numbers

pls give me the solution for this i need it for my exam pls pls pls Shell script to find the sum of first n Fibonacci numbers (1 Reply)
Discussion started by: Kshitija
1 Replies

7. Shell Programming and Scripting

problem in fibonacci series

hi, I'm a beginner to UNIX and got some problem in this fibonacci.Please help me out.Here is the code: fibo() { if then fibo=` expr {fibo ($1 - 2)} + {fibo ($1 - 1)}` | bc echo $fibo fi } echo "enter a number:" read x #echo "The fibonnacci series for value $x is:" fibo $x ... (4 Replies)
Discussion started by: janani_kalyan
4 Replies

8. Shell Programming and Scripting

How to generate a series of numbers

Hi All, I have a requirement where in I have an input as follows:- input=1-4,6,8-10,12-15 I need to explode this range into an output file as follows:- 1 2 3 4 6 8 9 10 12 13 14 15 My input may vary like 1,5-9,11-13,15-17....... (3 Replies)
Discussion started by: rony_daniel
3 Replies

9. UNIX for Dummies Questions & Answers

generate xml from a shell script

Hello! I would like to generate an xml file from the output of various commands generated from within a shell script (some will be in CDATA). At the moment the only solution I have come up with is echoing xml tags around the commands eg. echo "<bitism>" >> outputfile /usr/sbin/prtconf... (1 Reply)
Discussion started by: speedieB
1 Replies

10. Shell Programming and Scripting

Fibonacci series

Need code to run the Fibonacci series from 0 to 10 (16 Replies)
Discussion started by: nycol
16 Replies
Login or Register to Ask a Question