RustArena

Step 2 of 7

Integer division and remainder

In the first module you saw that 7 / 2 is 3. When both sides are integers, / is integer division: it divides and throws away the fractional part. The % operator (remainder, often called "modulo") gives what was left over:

fn main() {
    println!("{} {}", 7 / 2, 7 % 2);
    println!("{} {}", 17 / 5, 17 % 5);
    println!("{} {}", -7 / 2, -7 % 2);
}
3 1
3 2
-3 -1

Integer division truncates toward zero: -7 / 2 is -3, not -4. The remainder takes the sign of the left side, so -7 % 2 is -1.

Why this is useful

Integer division and remainder split a quantity into units:

fn main() {
    let total_minutes = 135;
    let hours = total_minutes / 60;
    let minutes = total_minutes % 60;
    println!("{total_minutes} min = {hours} h {minutes} min");

    let n = 1234;
    println!("last digit: {}", n % 10);
    println!("without it: {}", n / 10);
}
135 min = 2 h 15 min
last digit: 4
without it: 123

Patterns you'll use again and again:

Workplace note: for unsigned types (u8, u32, u64, ...), Rust also has n.is_multiple_of(k), which reads like the question it asks and doesn't panic when k is 0. Recent clippy versions suggest it over n % k == 0 (lint manual_is_multiple_of). This course mostly writes % k == 0, because it works for every integer type, signed ones included.

Dividing by zero

Integer division by zero has no answer, so Rust stops the program with a panic (a deliberate crash with a message), attempt to divide by zero. When the compiler can already see the zero, it refuses to compile instead (error: this operation will panic at runtime). Floats behave differently, as you'll see.

Common mistakes

Your task

A video is 754 seconds long. Use / and % on total_seconds to print it as minutes and seconds: 12 min 34 s. Don't type 12 or 34 yourself.

Challenge 2

Eggs are packed in boxes of 12. Fill in the operators so the program prints how many full boxes 98 eggs make and how many eggs are left over: Boxes: 8, left over: 2.

Challenge 3

Split the three-digit number n = 583 into its digits using only / and % (with 10 and 100), and print:

hundreds: 5, tens: 8, ones: 3

Previous: Integer types and literals Next: When numbers overflow