Remainder with Negative Integers

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

One. This is a common programming trick. Often you need to know the oddness and eveness of an integer.

Remainder with Negative Integers

The remainder operator can be used with negative integers. The rule is:

  1. Perform the operation as if both operands were positive.
  2. If the left operand is negative, then make the result negative.
  3. If the left operand is positive, then make the result positive.
  4. Ignore the sign of the right operand in all cases.

For example:

17 %  3 == 2     -17 %  3 == -2     
17 % -3 == 2     -17 % -3 == -2

You may wish to practice with the following:

Expression ResultExpression Result
7 -3 -7 5
-10 5 10 -6
-129 100 -1999 -100
-17 2 -18 2

QUESTION 17:

Five pirates find a chest of 123 gold coins and wish to divide the 123 coins evenly amoung themselves. How many coins does each pirate get?

The parrot gets any leftover coins. How many coins does the parrot get?