Java Glossary : modulus

CMP home Java glossary home Menu no menu Last updated 2004-06-28 by Roedy Green ©1996-2004 Canadian Mind Products

Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

You are here : home : Java Glossary : M words : modulus.

modulus
In Java you take the remainder with the % operator. This is usually called the modulus operator, though mathematicians would beg to differ, it is closer to a remainder operator. Java's modulus behaves, well, strangely. In Java, the sign of the remainder follows the dividend, not the divisor. Be especially careful when corralling random numbers into a smaller range with the modulus operator. It can produce a negative result! Java division does have the Euclidean property. When you multiply the quotient by the divisor and add the remainder you get back to the dividend. Java division is truncated division.

Mixed Base Calculations

The modulus operator is useful in time calculation. E.g. how many days, hours, minutes, seconds, milliseconds is 112,233,445,566,778,899 milliseconds?

static final int HOURS_PER_DAY = 24;
static final int MINUTES_PER_HOUR = 60;
static final int SECONDS_PER_MINUTE = 60;
static final int MILLISECONDS_PER_SECOND = 1000;

/* value to break down into hours, minutes, seconds, milliseconds */
long togo = 112233445566778899L; /* milliseconds */

int millis = (int)( togo % MILLISECONDS_PER_SECOND );
/* /= is just shorthand for togo = togo / 1000 */
togo /= MILLISECONDS_PER_SECOND;

int seconds = (int)( togo % SECONDS_PER_MINUTE );
togo /= SECONDS_PER_MINUTE;

int minutes = (int)( togo % MINUTES_PER_HOUR );
togo /= MINUTES_PER_HOUR;

int hours = (int)( togo % HOURS_PER_DAY );
int days = (int)( togo / HOURS_PER_DAY );

Going the other way from days, hours, minutes and seconds to milliseconds is easier. You just multiply each component by the appropriate factor:

static final long MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000L;
static final long MILLISECONDS_PER_HOUR = 60 * 60 * 1000L;
static final long MILLISECONDS_PER_MINUTE = 60 * 1000L;
static final long MILLISECONDS_PER_SECOND = 1000L;

long millis = days * MILLISECONDS_PER_DAY + hours * MILLISECONDS_PER_HOUR
              + minutes * MILLISECONDS_PER_MINUTE
              + seconds * MILLISECONDS_PER_SECOND
              + milliseconds;

a This is a rather simplistic answer to the problem. For more complicated answers see Calendar.

You can use similar logic to deal with other goofy mixed base systems like latitude and longitude with its degrees, minutes and seconds, yards, feet and inches or tons, pounds and ounces. APL has builtin operators to neatly handle these. In Java you have to code the conversions out longhand.

Sign Rules

Signs Division Modulus
+ + +7/+4=+1 +7%+4=+3
- + -7/+4=-1 -7%+4=-3
+ - +7/-4=-1 +7%-4=+3
- - -7/-4=+1 -7%-4=-3

Getting the digits of a Number, any Radix

Modulus can be used to take a number apart into digits, decimal, hexadecimal or any other base.

/**
 * Take a number apart into its digits.
 *
 * @param number the number to take apart into digits.
 * @param maxDigits maximum number of digits you wish returned.
 * @param base usually 10, which number base to use.
 * @return byte[] containing digits 0..base-1, least significant first,
 * Note it does not return characters, but signed byte numbers.
 */
static byte [] splitIntoDigits ( long number, int maxDigits, int base )
   {
   // byte array, least significant digit first, initialised to zeros.
   byte[] digits = new byte[maxDigits];
   // work right to left, peeling off digits.
   for ( int i=0; i<maxDigits; i++ )
      {
      if ( number == 0 ) break;
      digits [i]= (byte)( number % base );
      number /= base;
      } return digits;
   }

Even or Odd?

You can tell if an int is even or odd by looking at its remainder modulus 2:

boolean even = x % 2 == 0;
boolean odd = x % 2 != 0;

Note this similar code you often see posted will not work for negative numbers:

boolean even = x % 2 == 0;
boolean odd = x % 2 == 1; // does not work for negative x

There is a faster way to compute these, by masking off the low order bit:

boolean even = ( x & 1 ) == 0;
boolean odd = ( x & 1 ) != 0;

The code can be even faster if you want a number 0 or 1 as the result, say for indexing an array, instead of a boolean:

int odd = x & 1;

Other Uses

Modulus can be used in computing the next free circular squirrel cage buffer.

int nextbuf = ( thisbuf + 1 ) % supply;

Modulus can be used to turn an offset into a file into a chunk number and offset within that chunk.

int recordNumber = fileOffset / blockSize;
int recordOffset = fileOffset % blockSize;


CMP logo
CMP_home
home
Canadian Mind Products CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[24.87.56.253]
Your IP:[80.134.30.163]
You are visitor number 10983.
Please send errors, omissions and suggestions
to improve this page to Roedy Green.
You can get a fresh copy of this page from: or possibly from your local J: drive mirror:
http://mindprod.com/jgloss/modulus.html J:\mindprod\jgloss\modulus.html