Slides for P3724R1 — Integer division

Document number:
P3895R0
Date:
2025-03-11
Audience:
SG6
Project:
ISO/IEC 14882 Programming Languages — C++, ISO/IEC JTC1/SC22/WG21
Reply-to:
Jan Schultke <janschultke@gmail.com>
Source:
github.com/Eisenwave/cpp-proposals/blob/master/src/intdiv-slides.cow

This document has custom controls:

  • ,  ↓ : go to the next slide
  • ,  ↑ : go to previous slide

Integer division
P3724R1

Jan Schultke  |  Slides for P3724R1 — Integer division  |  Kona 2025  |  Slide 1

Introduction

int bucket_size = 1000, elements = 100; int buckets_req = elements / bucket_size; // WRONG, zero int buckets_req = div_to_inf(elements, bucket_size); // OK, one
Jan Schultke  |  Slides for P3724R1 — Integer division  |  Kona 2025  |  Slide 2

Why does this need to be in the standard?

[StackOverflowCeil] answer (67 upvotes) fails at rounding to +:

q = (x % y) ? x / y + 1 : x / y;

Mistake: incrementing negative quotients: x=-1, y=2, q=1

Jan Schultke  |  Slides for P3724R1 — Integer division  |  Kona 2025  |  Slide 3

Computing remainders is hard

The following function has unintended UB:

auto div_rem_ceil(_BitInt(4) x, _BitInt(4) y) { _BitInt(4) q = div_ceil(x, y); // round to + _BitInt(4) r = x - y * q; // overflow return div_result<_BitInt(4)> { q, r }; }

div_rem_ceil(7, 2) overflows: q == 4, y * q == 8

Jan Schultke  |  Slides for P3724R1 — Integer division  |  Kona 2025  |  Slide 4

Which rounding modes to support

div_to_zero📘(trunc) div_ties_to_zero
div_away_zero div_ties_away_zero📘(round)
div_to_inf📘(ceil) div_ties_to_inf
div_to_neg_inf📘(floor) div_ties_to_neg_inf
div_to_even⚖️ div_ties_to_even⚖️📘
div_to_odd⚖️ div_ties_to_odd⚖️
Jan Schultke  |  Slides for P3724R1 — Integer division  |  Kona 2025  |  Slide 5

Library interface

template<class T> struct div_result { T quotient, remainder; friend constexpr auto operator<=>(/* ... */) = default; }; template<class T> constexpr div_result<T> div_rem_mode(T x, T y); template<class T> constexpr T div_to_mode(T x, T y); template<class T> constexpr T mod(T x, T y);
Jan Schultke  |  Slides for P3724R1 — Integer division  |  Kona 2025  |  Slide 6

Other design considerations

Jan Schultke  |  Slides for P3724R1 — Integer division  |  Kona 2025  |  Slide 7

Implementation experience

Implementation is always in terms of / and %.

div_result<int> div_rem_to_neg_inf(int x, int y) { bool quotient_negative = (x ^ y) < 0; int adjust = int((x % y != 0) & quotient_negative); return { x / y - adjust, x % y + adjust * y }; }
Jan Schultke  |  Slides for P3724R1 — Integer division  |  Kona 2025  |  Slide 8

Questions

Jan Schultke  |  Slides for P3724R1 — Integer division  |  Kona 2025  |  Slide 9

References

[GitHub] Jan Schultke. integer-division GitHub repository https://github.com/Eisenwave/integer-division
[StackOverflowCeil] Fast ceiling of an integer division in C / C++ https://stackoverflow.com/q/2745074/5740428