Zig Integer Division
Integer division is division between whole numbers that gives a whole-number result.
The / operator truncates the fraction
Both divisions below have fractions. Both fractions are dropped.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
try out.print("{d}\n", .{7 / 2});
try out.print("{d}\n", .{8 / 3});
}@divTrunc and @rem split a division
@divTrunc gives the whole part. @rem gives the leftover.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
try out.print("{d}\n", .{@divTrunc(17, 5)});
try out.print("{d}\n", .{@rem(17, 5)});
}Negative division truncates toward zero
A negative result drops its fraction too. The remainder keeps the sign of the first number.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const a: i32 = -7;
const b: i32 = 2;
try out.print("{d}\n", .{a / b});
try out.print("{d}\n", .{@divTrunc(a, b)});
try out.print("{d}\n", .{@rem(a, b)});
}Example
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const total_minutes = 125;
const hours = @divTrunc(total_minutes, 60);
const minutes = @rem(total_minutes, 60);
try out.print("{d}\n", .{hours});
try out.print("{d}\n", .{minutes});
}Key points
- Truncation: dropping the fraction part of a result is called truncation.
- Use / to divide integers, and Zig truncates the result toward zero.
- Builtin: a builtin is a function built into Zig, and its name starts with @.
- Use @divTrunc(a, b) to divide with truncation and name the operation clearly.
- Use @rem(a, b) to get the remainder left after truncated division.
- Negative results: -7 / 2 gives -3, because truncation moves toward zero, not down.
In this example, @divTrunc divides 125 by 60 and gives 2 whole hours. @rem gives the 5 minutes left over. Together they split 125 minutes into 2 hours and 5 minutes.
Note
floor division would round -7 / 2 down to -4, so it gives a different answer from Zig.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does @rem(19, 6) give?