Skip to content

Instantly share code, notes, and snippets.

@smartwatermelon
Last active July 26, 2021 19:18
Show Gist options
  • Save smartwatermelon/fb3dada50015a5923d729a33723bf55c to your computer and use it in GitHub Desktop.
Save smartwatermelon/fb3dada50015a5923d729a33723bf55c to your computer and use it in GitHub Desktop.
@cassidoo's interview question from July 25, 2021
#!/usr/bin/env bash
set -eu -o pipefail
# Given a positive integer n, write a function that finds the number of zeros
# at the end of n! in base 10.
if [ $# -eq 0 ] || [ -n "$(printf '%s\n' "$1" | sed 's/[0-9]//g')" ]; then
echo "$(basename "$0"): enter a positive integer"
exit 1
fi
IN=$1
echo "you entered $IN"
F=$( BC_LINE_LENGTH=10000 bc <<< "$( seq -s '*' 1 "${IN}" | sed 's/*$//g' )" )
echo "factorial $IN is ${F}"
RF=$( rev <<< "${F}" )
COUNT=0
S=""
for (( i=0; i<${#RF}; ++i )); do
if [ "${RF:i:1}" -eq "0" ]; then
COUNT=$(( COUNT+1 ))
else
break
fi
done
if [ $COUNT -ne 1 ]; then S="s"; fi
echo "${F} ends with ${COUNT} zero${S}."
@smartwatermelon
Copy link
Author

MONTASIO:scripts andrewrich$ ./zerosEndingFactorial.sh 1
you entered 1
factorial 1 is 1
1 ends with 0 zeros.
MONTASIO:scripts andrewrich$ ./zerosEndingFactorial.sh 5
you entered 5
factorial 5 is 120
120 ends with 1 zero.
MONTASIO:scripts andrewrich$ ./zerosEndingFactorial.sh 100
you entered 100
factorial 100 is 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 ends with 24 zeros.

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