Some Simple Mathematical Tricks All Programmers Should Know

Or, "It's that easy??!!"

This is really basic stuff, so if it all sounds familiar, just skip it. If you haven't read these simple tricks, well, don't waste any time adding them to your arsenal!

[Ed.: Though the syntax used here is Java, understanding the code snippets should still be easy and these rules apply everywhere.]

Generating Values in the Range [0,n)

If you need to constrain the value of (say) an int variable to be in the range 0–n-1 (very useful when you are using the variable as an Array or List index) then modulus arithmetic can help you. Modulus arithmetic means that the value of x % n (where % is the modulus operator in many programming languages) will always be in the range [0, n):

for (int counter = 0; counter < 1000000; counter++) {
    int index = counter % n;
    //Do whatever. 0 <= index < n

Enforce a Lower Bound for a Variable's Value

This is very, very simple. Just use Math.max():

double y = Math.max(inputValue, minValue);

Huh? That seems counter-intuitive, right? Just think about it: Math.max will choose the greater value, and if inputValue < minValue, minValue will be returned, thereby ensuring that y is never less than minValue.

Enforce an Upper Bound for a Variable's Value

This is equally simple: we just use Math.min to ensure that x <= maxValue:

float x = Math.min(inputValue, maxValue);


Calculate Padding Value

Let's say you need to write out numbers that are padded with leading zeros such that the Strings you output look like 0001 to 9999 (often to right-align numbers in columnar text output). Simple:

String.format("%04d", counter);

This time you knew the largest number you had to accommodate beforehand. What if you wanted something more flexible, code which when told the largest number needed to be printed out could then work out the padding value (4 in the example above)?

Think back to high school arithmetic... logarithms specifically... log to the base 10 even more specifically... log of 9999 is 3.something... which is just one less than 4... hmm... what if we want to accommodate numbers up to 999 only? Log 999 is just under 3, take the floor of that and add 1 and we get 3, which is the padding value we wanted. Keeping in mind the pattern above, we can use:

int padding = ((int) Math.log10(largestNumber)) + 1;

Do watch out for the inaccuracies of floating point arithmetic though.

Invert the Meaning of compareTo/ strcmp

Most people that have programmed in a language with C-like syntax will be familiar with the strcmp function or the equivalent compareTo method. These functions/methods compare two strings and return a negative integer value if string1 comes before string2 in lexicographical order, a positive integer if string1 comes after string2, and 0 if both are equal.

What if in some situation you needed to reverse the meaning of the compareTo method? Super-simple! Just multiply the output by -1!