Skip to content

Instantly share code, notes, and snippets.

@smartwatermelon
Created June 22, 2022 23:07
Show Gist options
  • Save smartwatermelon/7bef1a92f485f79f2901d4029e2d6e78 to your computer and use it in GitHub Desktop.
Save smartwatermelon/7bef1a92f485f79f2901d4029e2d6e78 to your computer and use it in GitHub Desktop.
@cassidoo's 20220619 interview question
#!/usr/bin/env bash
set -eu -o pipefail
# return true if input is a perfect square
isPerfectSquare () {
square_root=$( bc <<< "sqrt ($1)" )
return $( [ $(( $square_root * $square_root )) == $1 ] )
}
# return true if num is Fibby
isFibby () {
if isPerfectSquare $plus4 || isPerfectSquare $minus4; then
return 0
else
return 1
fi
}
# return previous Fibby to passed num
getPrevFibby () {
x=$( bc <<< "(sqrt($plus4) + 0.5) / 1")
[ $(( $x * $x )) == $plus4 ] || x=$( bc <<< "(sqrt($minus4) + 0.5) / 1")
echo "$(( ($x - $NUM) / 2 ))"
}
# check for one and only one param
if [ $# -eq 0 ] || [ -n "$(printf '%s\n' "$1" | sed 's/[0-9]//g')" ]; then
echo "$(basename "$0"): enter a positive integer"
exit 1
fi
NUM=$1
plus4=$(( 5 * $NUM * $NUM + 4 ))
minus4=$(( 5 * $NUM * $NUM - 4 ))
if isFibby; then
echo "fibby"
else
echo "not fibby"
exit
fi
echo "prevFibby of $NUM is $( getPrevFibby )"
@smartwatermelon
Copy link
Author

MONTASIO:~ andrewrich$ ~/Documents/scripts/prevFib.sh 55
fibby
prevFibby of 55 is 34
MONTASIO:~ andrewrich$ ~/Documents/scripts/prevFib.sh 144
fibby
prevFibby of 144 is 89
MONTASIO:~ andrewrich$ ~/Documents/scripts/prevFib.sh 145
not fibby

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment