Exercism/bash/grains/grains.sh
2023-05-07 15:57:59 +02:00

34 lines
695 B
Bash

#!/usr/bin/env bash
# check if a command-line argument was provided
if [ -z "$1" ]
then
echo "Error: invalid input"
exit 1
fi
square=$1
# check if the square number is valid
if [[ "$square" != "total" ]] && (( square < 1 || square > 64 ))
then
echo "Error: invalid input"
exit 1
fi
if [[ $square == "total" ]]
then
total_grains=0
for ((square=1; square<=64; square++))
do
grains_on_square=$(echo "2^($square-1)" | bc)
# use floating point arithmetic (bc)
total_grains=$(echo "$total_grains + $grains_on_square" | bc)
done
echo $total_grains
else
grains_on_square=$(echo "2^($square-1)" | bc)
echo $grains_on_square
fi