The examples below use AP CSP Pseudocode. For Java, see Division operations.

AP CSP Pseudocode does not distinguish between integer and floating point division. The example given in the Exam Reference Sheet is 17 / 5 evaluates to 3.4.

Modular division

Modular division in AP CSP Pseudocode uses the MOD operator. The MOD operation is defined only for integers. The left operand is guaranteed to be ≥ 0. The right operand is guaranteed to be > 0.

Examples

22 MOD 5 evaluates to 2.
20 MOD 5 evaluates to 0.
20 MOD 20 evaluates to 0.
45 MOD 1234 evaluates to 45.

0 MOD 20 evaluates to 0.
20 MOD 0 is not defined (and would not be featured on the AP CSP Exam).

When a number is modularly divided by a larger number, the result is the original (smaller) number.

As with regular division, 0 can be the left operand for modular division but it cannot be the right operand.

Determining divisiblity

Modular division has many uses, including determining if a number is divisible by another number. The expression a MOD b = 0 evaluates to true if and only if a is divisible by b.

Wrapping a value

val ← RANDOM(0, 25)
k ← RANDOM(0, 99)
newVal ← (val + k) MOD 26

In the example above, newVal will always be in the range: 0 ≤ newVal ≤ 25

This technique is commonly used to wrap a value when it may exceed a maximum.

val k val + k (val + k) MOD 26
23 1 24 24
23 2 25 25
23 3 26 0
23 4 27 1

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on Division operations in AP CSP Pseudocode