Created
July 21, 2017 19:23
-
-
Save ggodreau/e40f50fd273ed3db6d5d7d8f9fed0d5f to your computer and use it in GitHub Desktop.
Bash script which generates n elements of the Fibonacci sequence, iteratively
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 | |
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 | |
F_n=0 # initial value of seq number | |
# subtract 2 from number of terms to deal with | |
# special case of seed terms | |
F_count=$(($F_count-2)) | |
echo -n "$F_1 " | |
echo -n "$F_2 " | |
for i in `seq $F_1 $F_2 $F_count` | |
do | |
F_n=$(($F_1+$F_2)) | |
echo -n "$F_n " | |
F_1=$F_2 | |
F_2=$F_n | |
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