17.7.5 Integer Division For High Precision Integers

The intdiv extension adds a single function named intdiv(), as follows:

@load intdiv

This is how you load the extension.

success = intdiv(numerator, denominator, result)

Perform integer division, similar to the standard C div() function. First, truncate numerator and denominator towards zero, creating integer values. Clear the result array, and then set result["quotient"] to the result of ‘numerator / denominator’, truncated towards zero to an integer, and set result["remainder"] to the result of ‘numerator % denominator’, truncated towards zero to an integer. Attempting division by zero causes a fatal error. Return zero upon success, and −1 upon error.

This function is primarily for use with arbitrary length integers; it avoids creating MPFR arbitrary precision floating-point values (see Arbitrary-Precision Integer Arithmetic with gawk).

The following example program, contributed by Katie Wasserman, uses intdiv() to compute the digits of pi to as many places as you choose to set. This program should be run with ‘gawk -M -f pi.awk’:

# pi.awk --- compute the digits of pi

@load "intdiv"

BEGIN {
    digits = 100000
    two = 2 * 10 ^ digits
    pi = two
    for (m = digits * 4; m > 0; --m) {
        d = m * 2 + 1
        x = pi * m
        intdiv(x, d, result)
        pi = result["quotient"]
        pi = pi + two
    }
    print pi
}

When asked about the algorithm used, Katie replied:

It’s not that well known but it’s not that obscure either. It’s Euler’s modification to Newton’s method for calculating pi. Take a look at lines (23) - (25) here: https://mathworld.wolfram.com/PiFormulas.html.

The algorithm I wrote simply expands the multiply by 2 and works from the innermost expression outwards. I used this to program HP calculators because it’s quite easy to modify for tiny memory devices with smallish word sizes. See https://www.hpmuseum.org/cgi-bin/articles.cgi?read=899.