Remainder

Another “classic” programming interview question.

The Question

Given a numerator and denominator, calculate the remainder.

The Answer

The Trivial Way:

This question is trivial if you use the modulus (%) operator. Simply read the user input, calculate and display the modulus and you are finished.

I added one simply check to ensure that the denominator is not equal to zero so that division can occur without error.

The final line simply shows the arithmetic expression (i.e. a = q*d + r ).

One note is that when calculating the remainder for negative numbers, there will be two possible answers which I did not bother to code.

#!/bin/bash
#set xv

read -p "Enter numerator: " numerator
read -p "Enter denominator: " denominator

(( $denominator == 0 )) && { echo "Denominator cannot be equal to 0!" >&2; exit 1; }

remainder=$((numerator % denominator))

echo "Remainder is: $remainder"
echo "i.e. $numerator=$denominator*$(( (numerator-remainder) / denominator ))+$remainder"

The Formula Way:

If for some reason you don’t (or can’t) use the modulus operator, you can always fall back on the arithmetic expression to calculate the remainder.

The method below exploits the way BASH does math: it only does integer math unless otherwise specified. Thus, 9/5=1, not 1.8. Using this, it is easy to write an expression that calculated the remainder by simply subtracting the largest whole multiple.

Again, this code suffers from the same issue as the one above, namely that it only calculates one of the remainders for negative numbers with the only error check on the denominator not being 0.

#!/bin/bash
#set -xv

read -p "Enter numerator: " numerator
read -p "Enter denominator: " denominator

(( $denominator == 0 )) && { echo "Denominator cannot be equal to 0!" >&2; exit 1; }

# BASH only preforms integer math unless otherwise specified so 9/5=1

remainder=$(( numerator- ( (numerator/denominator) * denominator) ))

echo "Remainder is: $remainder"
echo "i.e. $numerator=$denominator*$((numerator/denominator))+$remainder"

The Output

The output of both of the above scripts will be identical (or at least, they should be if they are coded properly).

Using the modulus:

$ ./remainder_modulus 
Enter numerator: 133419
Enter denominator: 234
Remainder is: 39
i.e. 133419=234*570+39

Using the formula:

$ ./remainder_formula 
Enter numerator: 133419
Enter denominator: 234
Remainder is: 39
i.e. 133419=234*570+39

Tests for a denominator equal to zero:

$ ./remainder_modulus 
Enter numerator: 12345
Enter denominator: 0
Denominator cannot be equal to 0!
$ ./remainder_formula 
Enter numerator: 12345
Enter denominator: 0
Denominator cannot be equal to 0!
Tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.

Protected by WP Anti Spam