Mathematics Book 1 Companion: Arithmetic and NumbersMaths Book 1 · Companion
0 / 0

Workbench / Mathematics Book 1 Companion: Arithmetic and Numbers

B1·04

Multiplying and Dividing

Around chapter 4: how multiplication and division connect to the rest of the book and to software, three other ways to see them, what the chapter simplifies (huge-number conversion as a security limit, ceiling division in floating point, rounding shares), how Python turns a 10,000-digit number into text by repeated division, four debugging drills, and interview questions.

6 topics · ~11 min read
Updated Suggest a correction

Understanding it better

Concept map

  • Multiplication = rectangles split by place value (distributivity) → long multiplication's shifted rows → binary's shift-and-add → Karatsuba's three-for-four trick.
  • Length of a product: m+n−1 or m+n digits → overflow when a fixed width is too small.
  • Division algorithm: a=qb+r, 0≤r<b, unique → long division ("bring down" is unbundling) → chapter 5's divisibility, gcd and modular arithmetic → chapter 7's repeating decimals.
  • Remainder conventions for negatives: floored, truncated, Euclidean.
  • The remainder's meaning depends on the story: round up, round down, share exactly (fractions, chapter 6), or ask "is it 0?".
  • In software: integer multiplication overflows silently in many languages; division is slow in hardware; % drives hashing, sharding, pagination and clocks; conversion between bases (printing a number) is repeated division.

Explain it differently

Floor tiles. 23×14 tiles split into four rectangles (20×10, 20×4, 3×10, 3×4) is long multiplication; laying 322 tiles in rows of 14 and counting the rows, taking away whole blocks of rows first, is long division.

A shopkeeper's scale. To weigh out 7,346 g of rice in 23 equal bags, you'd first put roughly 300 g in each bag (6,900 g), then share the 446 g left, about 10 g each, then the last 216 g, 9 g each, with 9 g left over. Long division is that: biggest portions first, then smaller ones from what's left.

Converting a number to text. A computer storing 7,346 in binary must divide by 10 again and again to print its decimal digits (chapter 2's repeated division). Every print of a number is a sequence of chapter 4 divisions; the code walkthrough shows how Python does it fast for numbers with thousands of digits.

Gaps and misconceptions

What the chapter oversimplifies

1. "Long division is slow but always possible", but converting huge numbers to text was slow enough to be a security hole. Turning a number into decimal digits is repeated division; done naively it takes time proportional to the square of the number of digits. In 2022 this became a denial-of-service problem (CVE-2020-10735): a request containing a number with a few hundred thousand digits could tie up a Python server. Python now refuses conversions above 4,300 digits by default:

Python
import json, sys
payload = '{"amount": ' + "9" * 5000 + '}'
try:
    json.loads(payload)
except ValueError as e:
    print("ValueError:", str(e)[:120])
print(sys.get_int_max_str_digits())
Text
ValueError: Exceeds the limit (4300 digits) for integer string conversion: value has 5000 digits; use sys.set_int_max_str_digits() t
4300

The limit is adjustable (sys.set_int_max_str_digits), and Python also added the faster algorithms in the code walkthrough. The lesson: the cost of arithmetic on unbounded input is an attack surface.

2. "Rounding up is ⌈n/k⌉", but in floating point that's only true for small numbers. Pagination and "how many buses" both need rounding up. The textbook formula through a float fails above 253:

Python
import math
n, size = 2**53 + 1, 1
print(math.ceil(n / size), (n + size - 1) // size, -(-n // size))
items, size = 10**17 + 1, 10
print(math.ceil(items / size), (items + size - 1) // size)
Text
9007199254740992 9007199254740993 9007199254740993
10000000000000000 10000000000000001

n / size is computed as a float first, which can't hold 253+1, so the ceiling of a rounded value is wrong. The integer forms (n + size - 1) // size and -(-n // size) are exact at any size. In code, round up with integer division.

3. "Sharing gives each person a÷b", but money can't be divided below a paisa. ₹100 shared by 3 is ₹33.33… each; rounding each share to the paisa loses money:

JavaScript
const share = Number((100 / 3).toFixed(2));
console.log(share, share * 3, Math.round(share * 3 * 100) / 100);
const paise = 10000, n = 3;
const base = Math.floor(paise / n), extra = paise % n;
console.log([...Array(n)].map((_, i) => base + (i < extra ? 1 : 0)));
Text
33.33 99.99 99.99
[ 3334, 3333, 3333 ]

Three shares of ₹33.33 make ₹99.99: a paisa vanishes. The fix is the division algorithm itself: 10000=3333×3+1, so two people pay 3,333 paise and one pays 3,334, which adds up exactly. Exercises C1 does it with tax.

Common misconceptions

Misconception What's actually true Where it's shown
"Printing a number is free." Converting to decimal is repeated division; naive conversion of huge numbers is slow enough that Python limits it to 4,300 digits by default. What the chapter oversimplifies, point 1
"math.ceil(n / k) rounds up correctly." Only while n / k is exact in floating point; use (n + k - 1) // k for integers. What the chapter oversimplifies, point 2
"Rounding each share to the paisa keeps the total." It can lose or invent paise; give the remainder to some shares explicitly. What the chapter oversimplifies, point 3
"Multiplying by 1,000,000 just adds zeros, even in JavaScript." Above 253, floats are spaced apart: nanosecond timestamps lose their last digits. Debugging drill D4
"10k has to be computed by multiplying tens." 10k=5k×2k, and multiplying by 2k is a shift: Python builds powers of ten that way. Code walkthrough

Theoretical gaps: the ideas behind the chapter

  • Cost models: the chapter counts single-digit products (n2 for long multiplication). Real costs depend on what's cheap on the machine; for numbers that fit in a register, one multiply instruction costs about as much as an add, so the asymptotic story only matters for big numbers.
  • Divide and conquer: Karatsuba and the conversion code below split a problem into halves, solve them, and combine. Analysing such recursions (the work at each level times the number of levels) is a basic tool of algorithm design.
  • Exactness and representation: integer division with remainder is exact; division producing a fraction needs chapter 6 (exact) or chapter 7 (decimals, possibly endless). Every "divide" in code silently chooses one of these.

Applying it

Code walkthrough

Python prints any integer in decimal, even one with ten thousand digits. For huge numbers it uses Lib/_pylong.py, a module of pure-Python algorithms added in Python 3.12 so that conversions take far less than quadratic time. Excerpts from Python 3.13 (on your computer: python3 -c "import _pylong; print(_pylong.__file__)").

Printing a huge number: divide in halves

Python
def int_to_decimal_string(n):
    """Asymptotically fast conversion of an 'int' to a decimal string."""
    w = n.bit_length()
    if w > 450_000 and _decimal is not None:
        # It is only usable with the C decimal implementation.
        # _pydecimal.py calls str() on very large integers, which in its
        # turn calls int_to_decimal_string(), causing very deep recursion.
        return str(int_to_decimal(n))

    # Fallback algorithm for the case when the C decimal module isn't
    # available.  This algorithm is asymptotically worse than the algorithm
    # using the decimal module, but better than the quadratic time
    # implementation in longobject.c.

    DIGLIM = 1000
    def inner(n, w):
        if w <= DIGLIM:
            return str(n)
        w2 = w >> 1
        hi, lo = divmod(n, pow10[w2])
        return inner(hi, w - w2) + inner(lo, w2).zfill(w2)

inner is chapter 2's repeated division, done with one big division instead of thousands of small ones: to print a number of about w digits, divide it by 10w/2. The quotient hi is the top half of the digits and the remainder lo the bottom half (the division algorithm guarantees lo is less than 10w/2, so it has at most w/2 digits). Print each half the same way, and pad the bottom half with leading zeros (zfill) because a remainder like 42 in a 4-digit half must print as 0042. Small enough pieces (1,000 digits) are left to the ordinary str.

Where the powers of ten come from

Python
    w = int(w * 0.3010299956639812 + 1)  # log10(2)
    pow10 = compute_powers(w, 5, DIGLIM)
    for k, v in pow10.items():
        pow10[k] = v << k # 5**k << k == 5**k * 2**k == 10**k

Two chapter ideas in three lines. The number of decimal digits is estimated from the number of bits times log102≈0.30103 (chapter 2's digit-count formula, changed from base 2 to base 10). And 10k is built as 5k shifted left k places, because 10k=5k×2k and multiplying a binary number by 2k is a shift. Measured:

Python
import _pylong
n = 3 ** 20000
s = _pylong.int_to_decimal_string(n)
print(len(s), s[:12], s[-12:])
k = 7
print(5**k << k, 10**k, (5**k << k) == 10**k)
print(int(n.bit_length() * 0.3010299956639812 + 1), len(str(n)) if False else len(s))
Text
9543 266130342721 253104400001
10000000 10000000 True
9543 9543

320000 has 9,543 digits, the estimate from its bit length is 9,543, and 57 shifted by 7 bits is exactly 107. (_pylong is a private module; it's called here only to look at it.)

Read it yourself

The reverse direction, text to number, is in the same file:

Python
def _str_to_int_inner(s):
    """Asymptotically fast conversion of a 'str' to an 'int'."""

    # Function due to Bjorn Martinsson.  See GH issue #90716 for details.
    # https://github.com/python/cpython/issues/90716
    #
    # The implementation in longobject.c of base conversion algorithms
    # between power-of-2 and non-power-of-2 bases are quadratic time.
    # This function implements a divide-and-conquer algorithm making use
    # of Python's built in big int multiplication. Since Python uses the
    # Karatsuba algorithm for multiplication, the time complexity
    # of this function is O(len(s)**1.58).

    DIGLIM = 2048

    def inner(a, b):
        if b - a <= DIGLIM:
            return int(s[a:b])
        mid = (a + b + 1) >> 1
        return (inner(mid, b)
                + ((inner(a, mid) * w5pow[b - mid])
                    << (b - mid)))

    w5pow = compute_powers(len(s), 5, DIGLIM)
    return inner(0, len(s))

w5pow[k] is 5k. Explain what inner(a, b) computes, why the left half is multiplied by w5pow[b - mid] and shifted by b - mid, and which chapter 2 method this is a version of.

Debugging drills

D1. An API that rejected a valid request

A Python service receives JSON from a partner. One request, a scientific dataset with an exact 5,000-digit integer, fails with ValueError (output in "What the chapter oversimplifies", point 1), and the partner calls it a bug. Is it? What are the options?

D2. The last page that disappeared

A reporting job computes the number of pages as math.ceil(total / page_size). For one very large export (output in "What the chapter oversimplifies", point 2), it produced one page fewer than needed and the last item was never exported. Explain and fix.

D3. The bill that came to ₹99.99

A JavaScript app splits a ₹100 bill three ways, rounding each share to two decimals (output in "What the chapter oversimplifies", point 3). Customers notice the shares add to ₹99.99. Fix it so the shares always add up.

D4. Timestamps that collide

A tracing system converts millisecond timestamps to nanoseconds in JavaScript by multiplying by 1,000,000, then adds small offsets to order events. Events 1 ns or 100 ns apart get the same timestamp:

JavaScript
const ms = 1764201600123;                 // a timestamp in milliseconds
const ns = ms * 1_000_000;                // the same instant in nanoseconds, as a Number
console.log(ns, Number.isSafeInteger(ns));
console.log(ns + 1 === ns, ns + 100 === ns, (ns + 1000) - ns);
const big = BigInt(ms) * 1_000_000n;
console.log(big + 1n, big + 1n === big);
Text
1764201600123000000 false
true true 1024
1764201600123000001n false

Explain the outputs, and fix it.

Career-oriented

Interview prep

Mid level

Q1. How do you compute "number of pages" for n items and page size k with integers, and why not with ceil(n / k)?

How to get there. State the formula, explain why it rounds up, and give the floating-point failure.

Q2. Explain what % does in your main language for negative numbers, and how you'd write a safe "wrap an index" function.

How to get there. Floored versus truncated, an example, and the portable formula.

Senior level

Q1. A cart service multiplies unit_price by quantity and occasionally reports negative totals. Walk through diagnosis and the long-term fix.

How to get there. Overflow, the length rule, and preventing it by design.

Q2. You need to split a ₹1,000 discount across an order's lines in proportion to their prices, in whole paise, so the parts add up to exactly ₹1,000. Describe the algorithm.

How to get there. Exact proportional shares, floor, then distribute the remainder.

Staff level

Q1. A colleague proposes sharding user data by user_id % N for a growing service. What do you say?

How to get there. What happens when N changes, and what the alternatives cost.

Q2. Your team must choose between float, decimal and integer minor units for a new billing system spanning several currencies. How do you decide?

How to get there. Exactness, division rules, currency differences, performance, interoperability.