Skip to content

Instantly share code, notes, and snippets.

@daper
Created March 21, 2017 22:26
Show Gist options
  • Save daper/e366d412b48aa82309a54fada78447b3 to your computer and use it in GitHub Desktop.
Save daper/e366d412b48aa82309a54fada78447b3 to your computer and use it in GitHub Desktop.
Bash implementation of Fast Doubling Fibonacci Series calculation. See: https://www.nayuki.io/page/fast-fibonacci-algorithms
#!/bin/bash
export BC_LINE_LENGTH=0
function fib() {
if [ $1 -lt 0 ]; then
echo "ERROR: Negative numbers not implemented"
exit 1
fi
read r ignore <<<$(_fib $1)
echo $r
}
function _fib() {
if [ $1 -eq 0 ]; then
echo "0 1"
else
read a b <<< $(_fib $(($1 / 2)))
c=$(bc <<< "$a * ($b * 2 - $a)")
d=$(bc <<< "$a * $a + $b * $b")
if [ $(bc <<< "$1 % 2") -eq 0 ]; then
echo "$c $d"
else
echo "$d $(bc <<< "$c + $d")"
fi
fi
}
# Get nth number of Fibonacci series
#eval fib $1
# Calculate Fibonacci series stating in 1
let i=1; while true; do echo "Fb($i): $(fib $i)"; ((i++)); done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment