Mathy Mathematicals

As you may notice a lot of programming requires math. Don't worry though as it's just some basic algebra and arithmetic you'll need for most problems. You'll need to know about the basic mathematical operators available along with the library of math functions available to you.

Operators

You know most of the operators. (*, /, +, -). Make sure you know how the division operator works when you work with division of integers. When you divide two integers, the answer will be truncated (rounded towards zero). For example 2 / 4 is 0 and 6 / 4 is 2. This only applies when the two numbers are of the type int, short, long, etc. If one of the operands is a float or double, division will be done just as a calculator does it.

There is one operator you may not know though and that's '%'. This is called the modulus, or remainder, operator. If you ever heard of modular arithmetic, it's similar to that. Don't worry, it's not a complex operator. It just returns the remainder of the left operand when divided by the right operand.

For example 3 % 5 is 3 and 6 % 4 is 2.

NOTE: The sign of the answer is always the sign of the left operand. This means that -3 % -2 is -1 and that 3 % -2 is 1 and that -3 % 2 is -1.

Math Library

Don't feel like you need to memorize all of these functions. You can always google the javadoc (even at competitions). The javadoc is always a resource at competitions as well as one book of your choice which you may bring. This means you'll always have this library at the tip of your fingers. Just know the important ones such as sqrt and pow.

Function Purpose Return Type
Math.abs(x) Returns the absolute value of x Same as the parameter.
Math.ceil(x) Rounds x up to an integer double
Math.floor(x) Rounds x down to an integer double
Math.round(x) Rounds xto the nearest integer int or long, depends on what x is
Math.log(x) Returns log base e of x double
Math.max(x, y) Returns the larger of x and y Same as the parameters
Math.min(x, y) Returns the smaller of x and y Same as the parameters
Math.sqrt(x) Returns the square root of x double
Math.pow(x, y) Returns x to the power of y double
Math.random() Returns a random number between 0 and 1 but never equal to 1 double

Notice how ceil and floor return double, so you have to cast to an int if the result is going to be stored in an int.

The two constants E and PI are also in the Java Math class.

results matching ""

    No results matching ""