Created
June 22, 2022 23:07
-
-
Save smartwatermelon/7bef1a92f485f79f2901d4029e2d6e78 to your computer and use it in GitHub Desktop.
@cassidoo's 20220619 interview question
This file contains hidden or 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
#!/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 )" |
Author
smartwatermelon
commented
Jun 22, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment