Created
July 21, 2017 19:24
-
-
Save ggodreau/90e9d04c1ba700addb8a43fd23e9eb61 to your computer and use it in GitHub Desktop.
Bash script which generates n elements of the Fibonacci sequence, recursively
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# source https://en.wikipedia.org/wiki/Fibonacci_number | |
# assuming F_1 = 1 and F_2 = 1 for seed values | |
# recursion function | |
function fib_recur_func(){ | |
local F_n F_1 F_2 # Avoid leaking to main scope | |
F_n=$1 | |
# base case | |
if ((F_n < 2)) | |
then | |
((base=F_n)) | |
# iterator | |
else | |
F_1=$(fib_recur_func "(($F_n - 1))") | |
F_2=$(fib_recur_func "(($F_n - 2))") | |
((base=F_1+F_2)) | |
fi | |
echo -n "$base " | |
base=0 | |
} | |
# Main | |
read -p "Enter Count of Fibonacci Terms: " F_count | |
# input checking | |
re='^[0-9]+$' | |
if ! [[ $F_count =~ $re ]] ; then | |
echo "Not a valid integer, exiting..." >&2; exit 1 | |
fi | |
# begin script | |
F_1=1 | |
F_2=1 | |
for i in `seq $F_1 $F_2 $F_count` | |
do | |
fib_recur_func "$i" | |
done | |
# carriage return / line feed cleanup | |
echo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment