man number-theory/integer-division
lesson 2 of 27 · Divisibility and the Euclidean algorithm
Integer division, floors and ceilings
How many multiples of 4 lie between −9 and 13? Counting by hand gives 6: −8, −4, 0, 4, 8, 12. The formula that does it for ranges of length is one line, , and it gives 5 if you type it into C++. This lesson pins down what integer division means for every sign, in Python and in C++, then uses floors and ceilings to count, and ends with integer square roots, where floats fail quietly from about on.
The code is in cp-math at tag lesson-02,
in cpmath/division.py. Its tests compare every function with brute force,
and python3 -m cpmath.lesson02 prints every Python output on this page. The
C++ output comes from demos/division.cpp in the same repo.
Division with remainder
Dividing 17 by 5 gives quotient 3 and remainder 2: . For negative numbers there are two reasonable answers, and languages disagree, so it pays to start from the theorem that fixes one of them.
Theorem (division with remainder). For integers and there is exactly one pair of integers with
and , the largest integer that is at most .
Proof. Existence: take and . From , multiplying by gives , so . Uniqueness: if with both remainders in , then , and . The only multiple of strictly between and is 0, so and .
Python follows this theorem: a // b is for every
sign of and , a % b is what is left, and
a == (a // b) * b + a % b always holds. The language reference says so in
those words. For the floor still decides, and the remainder then
lies in : it always has the sign of the divisor.
7 // 3 = 2 7 % 3 = 1 trunc_div = 2 trunc_mod = 1
-7 // 3 = -3 -7 % 3 = 2 trunc_div = -2 trunc_mod = -1
7 // -3 = -3 7 % -3 = -2 trunc_div = -2 trunc_mod = 1
-7 // -3 = 2 -7 % -3 = -1 trunc_div = 2 trunc_mod = -1
divmod(-7, 3) -> (-3, 2)
The last two columns are what C++ computes, as the next section shows.
What C++ does instead
In C++, / on integers truncates toward zero: it drops the fractional part,
so becomes , not . The remainder is defined
by the same identity, (a / b) * b + a % b == a, so it takes the sign of the
dividend: -7 % 3 is . The standard has required this since C++11;
C++98 left the rounding direction to the implementation, and cppreference
lists the change as a defect report against C++98.
Both conventions agree when the true quotient is non-negative. They differ
exactly when the quotient is negative and not an integer, and then truncation
is one more than the floor. That gives the conversions, copied from
demos/division.cpp:
long long floor_div(long long a, long long b) {
long long q = a / b;
if (a % b != 0 && ((a < 0) != (b < 0))) q--;
return q;
}
long long ceil_div(long long a, long long b) {
long long q = a / b;
if (a % b != 0 && ((a < 0) == (b < 0))) q++;
return q;
}
// The remainder Python's % gives: 0 <= r < b for b > 0.
long long floor_mod(long long a, long long b) {
long long r = a % b;
if (r != 0 && ((r < 0) != (b < 0))) r += b;
return r;
}
ceil_div is the mirror image: truncation equals the ceiling when the
quotient is negative or exact, and is one less than it otherwise. The demo
checks all three against a search over every pair with
. Built with Apple clang 21 for
arm64 (clang++ -std=c++17 -fsanitize=undefined), it prints:
demos/division.cpp:93:15: runtime error: division of -2147483648 by -1 cannot be represented in type 'int'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior demos/division.cpp:93:15
C++ / and % on every sign:
7 / 3 = 2 7 % 3 = 1
-7 / 3 = -2 -7 % 3 = -1
7 / -3 = -2 7 % -3 = 1
-7 / -3 = 2 -7 % -3 = -1
floor_div, ceil_div, floor_mod: 14520 pairs checked, 0 wrong
floor_div(-7, 3) = -3, ceil_div(-7, 3) = -2, floor_mod(-7, 3) = 2
(a + b - 1) / b with a = -7, b = 3: -1 (the ceiling is -2)
multiples of 4 in [-9, 13]: hi / k - (lo - 1) / k = 5, with floor_div: 6
sizeof(double) = 8, sizeof(long double) = 8, LDBL_MANT_DIG = 53
n = 999999999999999999: (long long)sqrt(n) = 1000000000, (long long)sqrtl(n) = 1000000000, isqrt(n) = 999999999
n = 4503599761588224: (long long)sqrt(n) = 67108865, (long long)sqrtl(n) = 67108865, isqrt(n) = 67108864
n = 9223372036854775807: (long long)sqrt(n) = 3037000499, (long long)sqrtl(n) = 3037000499, isqrt(n) = 3037000499
isqrt: 6915968 values checked, 0 wrong
INT_MIN / -1 = -2147483648
The sanitizer’s complaint is about the last line. It comes first here
because this output was captured to a file, where the program’s own output
is buffered and the sanitizer’s is not; on a terminal it appears just before
the last line. Two divisions are undefined behaviour in
C++: by zero, and any whose quotient does not fit the type. The only such
quotient for int is . This build printed
, but undefined means a different compiler or flag may do anything
else. Python raises ZeroDivisionError for the first and has no second.
Going the other way, a Python solution sometimes has to reproduce C’s truncation, because a problem defines division that way:
def trunc_div(a, b):
"""a / b rounded toward zero, as C and C++ do (b != 0)."""
q = abs(a) // abs(b)
return q if (a < 0) == (b < 0) else -q
def trunc_mod(a, b):
"""The remainder that goes with trunc_div: C and C++'s a % b.
It has the sign of a, and a == trunc_div(a, b) * b + trunc_mod(a, b)."""
return a - trunc_div(a, b) * b
The shortcut int(a / b) gives the same result as long as
, which covers 32-bit inputs. The reason: CPython
rounds a / b on ints to the nearest double (CPython issue 1811).
If is not an integer it is at least away from
one, while rounding moves it by at most half the spacing of doubles there,
which is at most . So
rounding never reaches the next integer. The tests check this on 20,000 random pairs.
Above it fails, as the next section shows.
Ceilings without floats
Some answers are a ceiling: how many boxes of size hold items, how many hours a pile takes at a given speed. Negating turns a ceiling into a floor, , and in Python that is one expression:
def ceil_div(a, b):
"""The ceiling of a / b, for any integers a and b != 0."""
return -(-a // b)
The other common form is
for . Proof: write with . If ,
then , whose floor is . If
, then with
, so the floor is .
The proof uses the floor, so in C++ use it only for
: the demo above shows (-7 + 3 - 1) / 3 giving where the
ceiling is . It can also overflow when is near the top of the
type.
What not to write is math.ceil(a / b). The / converts to a double, which
has 53 bits of mantissa, so integers above are
not all representable:
a = 10**18 + 1, b = 2: math.ceil(a / b) = 500000000000000000, ceil_div(a, b) = 500000000000000001
int((10**18 - 1) / 1) = 1000000000000000000, (10**18 - 1) // 1 = 999999999999999999
Both errors are silent. With integers up to , the common contest
limit, every division should stay in //.
Two identities for floors
Two facts about floors come up in almost every derivation. For a real and an integer ,
because is an integer at most , and the next integer up is more than . And dividing twice is dividing once by the product: for an integer and integers ,
Proof. Divide twice with remainder: with , then with . Then , and . By the uniqueness in the theorem, is the quotient of by .
So n // a // b == n // (a * b) for every sign of n, which is handy when
a * b would overflow in C++. C++’s truncation obeys the same identity: for
negative it is minus the floor of , and the identity holds for
.
1000 // 7 // 11 = 12, 1000 // 77 = 12
-1000 // 7 // 11 = -13, -1000 // 77 = -13
Counting multiples in a range
The multiples of are the numbers for integers . The largest one that is at most is : by the definition of the floor, exactly when . So the multiples in are for from to , and there are
of them, for any , negative or not. The figure steps through it, then repeats the subtraction with C++’s truncation:
The integers from -13 to 14 with the range -9 to 13 outlined. The multiples of 4 in it, -8, -4, 0, 4, 8, 12, are marked with their indices -2 to 3. 13 // 4 = 3 points at 12 and -10 // 4 = -3 points at -12; truncation instead points at -8, which is then missed. (This figure steps through a recorded run; it needs JavaScript.)
Counting the multiples of 4 in . Trace from python3 -m cpmath.multiples_trace -9 13 4 in cp-math.
In C++, truncates to , pointing at , which is inside
the range, so is not counted. With both numerators are
non-negative and plain / is fine; with possibly negative , use
floor_div. In Python:
def count_multiples(lo, hi, k):
"""How many multiples of k (k > 0) lie in [lo, hi]. Any signs."""
if lo > hi:
return 0
return hi // k - (lo - 1) // k
def count_congruent(lo, hi, r, k):
"""How many x in [lo, hi] have x % k == r % k (k > 0)."""
return count_multiples(lo - r, hi - r, k)
The second function shifts the range: means , and runs over . Numbers divisible by or are counted by adding both counts and subtracting the numbers counted twice, which are the multiples of (lesson 1); exercise 3 below is one. On this section’s examples:
multiples of 4 in [-9, 13]: [-8, -4, 0, 4, 8, 12]
13 // 4 = 3 (-9 - 1) // 4 = -3 count = 6
C++-style: trunc(13 / 4) - trunc(-10 / 4) = 3 - (-2) = 5
multiples of 7 in [10**18, 2*10**18]: 142857142857142857
x in [1, 100] with x % 7 == 3: 14 [3, 10, 17] ...
The tests compare count_multiples with a loop over the range for every
and , and on 2,000 random short ranges
starting anywhere in ; and count_congruent for every
, and .
Integer square roots
The integer square root of is , the
largest with . Python has it as math.isqrt (since 3.8;
in 3.15 it is math.integer.isqrt, and math.isqrt is the same function,
kept as a soft-deprecated alias). The tempting int(math.sqrt(n)) goes
through a double and can be off by one:
int(math.sqrt(10**18 - 1)) = 1000000000, math.isqrt = 999999999, isqrt = 999999999
k = 67108865, n = k*k - 1 = 4503599761588224: int(math.sqrt(n)) = 67108865, math.isqrt(n) = 67108864
The first fails because is not a double: it rounds to
before the square root is taken. The second fails even though
is exact: is about , and
when , is less than half the spacing of doubles near
, so the correctly rounded square root is itself. A scan of every
(python3 -m cpmath.lesson02 --scan, eight seconds) finds
to be the first for which fails.
That also shows that nothing below
fails: below , int(math.sqrt(n)) never decreases as grows
and is never below the right answer, so if it fails anywhere on a stretch
, it also fails at the stretch’s last number.
Newton’s method in integers computes it exactly for any size:
def isqrt(n):
"""The largest x with x*x <= n, for an integer n >= 0, by Newton's
method on integers. Every step is exact, so this works for any size.
It starts at a power of two that is at least sqrt(n). From any
x >= isqrt(n) the next value never drops below isqrt(n), and it is
strictly smaller while x > isqrt(n); so the loop stops exactly at
isqrt(n).
"""
if n < 0:
raise ValueError("isqrt of a negative number")
if n == 0:
return 0
x = 1 << ((n.bit_length() + 1) // 2) # n < 2**bits, so x > sqrt(n)
y = (x + n // x) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x
Why it is correct. Let and . The step computes with (the first identity). By the inequality of arithmetic and geometric means, , and is an integer, so and : the iteration never undershoots. If , then , so and , so , and . The start is at least , so the values strictly decrease while they are above and never go below it; the loop stops only when , which can happen only at .
It converges fast; the counts are steps after the starting power of two:
isqrt_steps(10**18 - 1) = [1073741824, 1002532199, 1000003197, 1000000000, 999999999]
steps after the start: 10**18 - 1: 4 2**200: 6 3**2000: 8
In C++ there is no isqrt. Take the floating-point guess and correct it,
comparing by division so that never has to fit:
long long isqrt(long long n) {
long long r = (long long)std::sqrt((double)n);
while (r > 0 && r > n / r) r--; // r*r > n
while (r + 1 <= n / (r + 1)) r++; // (r+1)*(r+1) <= n
return r;
}
The demo checks it at , and for every
up to , every 9973rd after that, and the last thousand
up to the largest square in a long long: 6,915,968 values.
A common fix is sqrtl, but on this machine long double is the same 64-bit
type as double (LDBL_MANT_DIG = 53 above), so sqrtl fails in the same
places. The correction loops do not depend on how good the first guess is.
Two uses. The number of perfect squares in for is
, the same subtraction
as for multiples. And the smallest with , for , is
1 + math.isqrt(n - 1), as the Python documentation suggests.
Practice problems
Each needs an idea from this lesson. Links go to the problem pages; the one line is what to use, not the statement.
- Codeforces 1A. Theatre Square: a product of two ceiling divisions.
- LeetCode 875. Koko Eating Bananas: the time at a given speed is a sum of ceilings; binary search on the speed.
- LeetCode 1870. Minimum Speed to Arrive on Time: ceilings for every ride but the last; compare in hundredths of an hour to keep floats out.
- Codeforces 1471A. Strange Partition: the ceiling of a sum is at most the sum of the ceilings.
- LeetCode 150. Evaluate Reverse Polish Notation: the problem’s division truncates, so
//is wrong on negative operands; usetrunc_div. - LeetCode 29. Divide Two Integers: truncation toward zero, and the one 32-bit quotient that does not fit.
- Codeforces 597A. Divisibility: the multiples of in a range with negative ends, exactly the formula above.
- LeetCode 2894. Divisible and Non-divisible Sums Difference: there are multiples of up to , and their sum has a closed form.
- LeetCode 1201. Ugly Number III: count the numbers up to divisible by one of three, with floors and lcms; binary search on .
- Codeforces 1342C. Yet Another Counting Problem: the condition repeats with period ; count up to and up to with one floor division by the period.
- LeetCode 69. Sqrt(x): the integer square root, by Newton’s method or binary search.
- LeetCode 633. Sum of Square Numbers: for each , test whether is a perfect square with
isqrt.
Try it yourself
- What are
17 // -5,17 % -5,-17 // 5and-17 % 5in Python? What are-17 / 5and-17 % 5in C++? - How many integers in are multiples of 7? How many leave remainder 3 when divided by 7 (in Python’s sense)?
- How many integers in are divisible by 6 or by 10?
- Prove that for integers and .
- How many perfect squares lie in ?
- In C++,
(a % b + b) % bis a common way to get Python’sa % bfor . Why does it work, and for whichlong longvalues of can it overflow?
Answers
Each one is asserted in tests/test_lesson02.py, by brute force where the
numbers are small enough.
Show the answers
- Python: , , , . C++: and .
- 29 multiples (), and 28 numbers with remainder 3 (from to 94).
- for , since .
- Write with . If , then , so the right side is . If , then with , so the right side is .
- 683772234: .
a % blies in and has the right remainder mod ; adding keeps the remainder and makes the value positive, and C++’s%on non-negative numbers agrees with Python’s. The suma % b + bis less than , so it cannot overflow for . For larger it can: , gives a sum above .
Sources
- Python language reference, Binary arithmetic operations:
//is division with the floor applied,%has the sign of its second operand, andx == (x//y)*y + (x%y). - Python documentation: math.integer (
isqrt, and1 + isqrt(n - 1)for the ceiling) and math (the soft-deprecated aliases,isqrtadded in 3.8). - cppreference, Arithmetic operators: integer division truncates toward zero,
(a / b) * b + a % b == a, and division by zero or an unrepresentable quotient is undefined; the defect reports CWG 614 and 1450. - Python issue 1811, “True division of integers could be more accurate”: the change that made
a / bon ints correctly rounded. - Wikipedia, Euclidean division: the division theorem and its proof.
- Wikipedia, Floor and ceiling functions, sections “Equivalences”, “Quotients” and “Nested divisions”: , for , and the nested-division identity.
- Wikipedia, Integer square root: Newton’s method with integer division (section “Using only integer division”) and the rule of stopping at the first with (section “Generalization to Nth roots”).
- R. L. Graham, D. E. Knuth, O. Patashnik, Concrete Mathematics, 2nd ed., chapter 3, “Integer Functions”: floors, ceilings and their identities at length.
ls number-theory/
Divisibility and the Euclidean algorithm
- 01 GCD, Euclid, and Bézout draftWhy gcd(a, b) = gcd(b, a mod b), why it takes so few steps, extended Euclid and ax + by = c. Unlocks gcd-of-array, water jug and lcm problems.
- 02 Integer division, floors and ceilings draft// and % on negative numbers in Python and C++, ceiling division without floats, math.isqrt. Unlocks problems whose answer is a count of multiples in a range.
- 03 GCD over arrays and subarrays draftPrefix and suffix gcds, the gcd of differences, why a subarray's gcd changes only a logarithmic number of times. Unlocks subarray-gcd counting and remove-one-element problems.
Primes and factorization
- 04 Primality and factoring by trial division draftWhy checking up to the square root suffices, and how far that goes in a time limit. Unlocks single-number primality and factorization queries.
- 05 The sieve of Eratosthenes plannedCrossing out multiples from p squared, its n log log n cost, and a fast bytearray version in Python. Unlocks prime counting and prime listing up to about ten million.
- 06 The linear sieve plannedEach composite crossed out exactly once, by its smallest prime factor, with multiplicative functions computed in the same pass.
- 07 Smallest-prime-factor sieve plannedStore each number's smallest prime factor and factor any number below the limit in logarithmic time. Unlocks problems that factor many numbers.
- 08 The segmented sieve plannedPrimes in a window [L, R] with R far beyond what fits in memory, using only the primes up to the square root of R.
- 09 Number and sum of divisors plannedBoth from the prime factorization, listing all divisors, and the harmonic-series sieve that does it for every n at once. Unlocks divisor-counting and perfect-number problems.
- 10 Prime powers in factorials plannedLegendre's formula for the exponent of p in n!. Unlocks trailing-zero and divisibility-of-factorial problems.
Modular arithmetic
- 11 Arithmetic mod m plannedCongruences, the remainder of a negative number, which operations survive reduction, and why so many problems use 10^9 + 7.
- 12 Fast exponentiation plannedSquare-and-multiply, Python's three-argument pow, and matrix powers for linear recurrences. Unlocks huge-exponent and n-th Fibonacci problems.
- 13 Modular inverses plannedDivision mod m by Fermat's little theorem and by extended Euclid, when an inverse exists, and all inverses of 1..n in linear time.
- 14 Euler's totient and Euler's theorem plannedCounting the numbers coprime to n, by formula and by sieve, and reducing exponents mod phi(m). Unlocks power towers mod m.
- 15 Linear congruences plannedSolving a x ≡ b (mod m), how many solutions there are, and when there are none.
- 16 The Chinese remainder theorem plannedCombining congruences into one, for coprime and non-coprime moduli. Unlocks problems with several periodic conditions.
- 17 Orders, primitive roots and discrete logarithms plannedThe order of an element, finding a generator, and baby-step giant-step for a^x ≡ b (mod m).
Counting mod p
- 18 Factorials, inverse factorials and nCr plannedPrecompute factorials and their inverses once, then answer each binomial coefficient in constant time. Unlocks most counting problems with a prime modulus.
- 19 Binomial identities and Pascal's triangle plannedPascal's rule for composite moduli, stars and bars, and Catalan numbers.
- 20 Lucas's theorem plannednCr mod a small prime p when n is far larger than p, digit by digit in base p.
- 21 Inclusion–exclusion plannedCounting by alternating sums over subsets: numbers coprime to n in a range, derangements, surjections.
- 22 The Möbius function and Möbius inversion plannedInclusion–exclusion over divisors. Unlocks counting coprime pairs and sums of gcds.
- 23 Divisor blocks: iterating over n // i plannedn // i takes only about 2 sqrt(n) distinct values; summing over blocks of equal value turns many O(n) sums into O(sqrt n).
- 24 Sums over gcds plannedSums of gcd(i, n) and of gcd(i, j) over a grid, by grouping on the gcd and using the totient and Möbius function.
Large numbers
- 25 The Miller–Rabin primality test plannedA probabilistic test, and a fixed set of bases that makes it exact for every 64-bit number. Unlocks primality checks up to 10^18.
- 26 Pollard's rho factorization plannedFactoring 64-bit numbers by finding a cycle in a pseudo-random sequence, with Brent's improvement.
- 27 Floor sums by a Euclid-like recursion plannedThe sum of floor((a i + b) / m) over a range in logarithmic time, by the same reduction Euclid's algorithm uses. Unlocks lattice-point counting under a line.