Programming Search⌘K

Taskintro

Return multiple values

Also called multiple return values, return a tuple, return two values, divmod, out parameters, tuple return.

Return the quotient and the remainder of a floor division from one function, as a tuple, a record, a struct or out parameters, and unpack the two results at the call.

Task

Define a function div_mod(a, b) that returns two results, the quotient and the remainder of the division of a by b. The caller gets both results from one call and unpacks them into two variables.

The division is floor division, as in the Python function divmod: "For integers, the result is the same as (a // b, a % b)."1 For //, "the result is that of mathematical division with the ‘floor’ function applied to the result"2, and "The modulo operator always yields a result with the same sign as its second operand"2. Java describes the same remainder: it "has the same sign as the divisor y or is zero, and is in the range of -abs(y) < r < +abs(y)."3

For example, div_mod(17, 5) is (3, 2), div_mod(-17, 5) is (-4, 3) and div_mod(17, -5) is (-4, -3). The arguments and the results are 32-bit signed integers. b is not 0, and the pair a = -2147483648, b = -1 is not allowed, because its quotient 2147483648 does not fit. Java says that for this pair "integer overflow occurs and the result is equal to Integer.MIN_VALUE."3

Many languages round the quotient of / toward zero. "Despite the mathematical elegance of Knuth's floored division and Euclidean division, it is generally much more common to find a truncated division-based modulo in programming languages."4 So some solutions change the result of / and %: when the remainder is not 0 and its sign is not the sign of b, they subtract 1 from the quotient and add b to the remainder.

In most of the solutions below, the function returns one value that holds both results, such as a Tuple or a record, and the caller takes it apart again. Return value describes the result of a function, and Destructure a value shows more ways to unpack a value.

Solutions

Language The two results The unpack at the call
Python a tuple, return a // b, a % b q, r = div_mod(a, b)
JavaScript an array, return [q, r] const [q, r] = divMod(a, b)
TypeScript the tuple type [number, number] const [q, r] = divMod(a, b)
Java the record QuotientAndRemainder(int quotient, int remainder) result.quotient() and result.remainder()
C# the tuple type (int Quotient, int Remainder) var (q, r) = Division.DivMod(a, b)
C the out parameters int *quotient, int *remainder div_mod(a, b, &q, &r)
C++ the struct div_mod_result auto [q, r] = div_mod(a, b)
Go the result list (int32, int32) q, r := DivMod(a, b)
Rust the tuple type (i32, i32) let (q, r) = div_mod(a, b);
Bash one line of output, echo "$q $r" read -r q r
  • Python. "The statement t = 12345, 54321, 'hello!' is an example of tuple packing"5. The statement return a // b, a % b packs the two results in the same way. At the call, q, r = div_mod(a, b) does the reverse: "This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side."5 The operators // and % already give floor results2, and the built-in divmod returns the same pair1.
  • JavaScript. The function returns an array of two numbers. "The destructuring syntax is a JavaScript syntax that makes it possible to unpack values from arrays, or properties from objects, into distinct variables."6 The remainder operator does not give the floor result: "It always takes the sign of the dividend."7 So the solution changes the quotient and the remainder as the Task section describes.
  • TypeScript. The return type [number, number] is a tuple type. "A tuple type is another sort of Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions."8 So the type checker knows that the result has two numbers.
  • Java. The solution returns a record. "Record classes, which are a special kind of class, help to model plain data aggregates with less ceremony than normal classes."9 For a record, "the appropriate accessors, constructor, equals, hashCode, and toString methods are created automatically."9 The caller reads the results with quotient() and remainder(). Math.floorDiv and Math.floorMod give floor results: "Normal integer division operates under the round to zero rounding mode (truncation). This operation instead acts under the round toward negative infinity (floor) rounding mode."3
  • C#. The solution returns a tuple with named fields. "One of the most common use cases for tuples is as a method return type."10 The caller can "work with the returned tuple instance directly or deconstruct it in separate variables."10 Out parameters are another way: "To use an out parameter, both the method definition and the calling method must explicitly use the out keyword."11
  • C. The solution writes the two results through pointer parameters. Effective Go calls this "modifying an argument passed by address" and names it one of "a couple of clumsy idioms in C programs"12. The standard function div returns a structure instead. It "Computes both the quotient (the member quot) and the remainder (the member rem) of the division of the numerator x by the denominator y."13 But / gives the quotient "truncated towards zero"14, so the solution changes the result.
  • C++. The solution returns a struct with two named fields, and the caller unpacks it with a structured binding. A structured binding "Binds the specified names to subobjects or elements of the initializer."15 A std::pair also works: "std::pair is a class template that provides a way to store two heterogeneous objects as a single unit."16 Its fields are first and second, so the struct gives clearer names.
  • Go. "One of Go's unusual features is that functions and methods can return multiple values."12 The result list (int32, int32) comes after the parameters, and q, r := DivMod(a, b) assigns both results. The Go operator / gives a quotient "truncated towards zero"17, so the solution changes the result.
  • Rust. "Rust does let us return multiple values using a tuple"18. "A tuple is a general way of grouping together a number of values with a variety of types into one compound type."19 The pattern let (q, r) = div_mod(a, b); unpacks it. "Integer division truncates toward zero to the nearest integer."19 So the solution changes the result.
  • Bash. A Bash function cannot return two numbers. The solution prints them on one line, and the caller reads the line with read. The read builtin will "split it into words as described above in Word Splitting, and assign the first word to the first name, the second word to the second name, and so on."20

Unpack the results or keep them together

The caller can unpack the tuple into two names, or keep it as one value and index it:

def div_mod(a: int, b: int) -> tuple[int, int]:
    return a // b, a % b


q, r = div_mod(-17, 5)
print(q, r)

result = div_mod(17, 5)
print(result)
print(result[0], result[1])
Output
-4 3
(3, 2)
3 2

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • negative-dividend, negative-divisor and both-negative: the signs of 17 and 5 change. The remainder takes the sign of b, so the results are (-4, 3), (-4, -3) and (3, -2).
  • small-negative: -3 divided by 10 gives (-1, 7). A truncated division gives (0, -3).
  • exact-negative: -20 divided by 4 has the remainder 0, so the solution does not change the quotient -5. In JavaScript, the remainder is -0, as in the MDN example -4 % 2; // -07. The JavaScript solution adds 0 to each result, so the result is 0.
  • zero-dividend and zero-negative-divisor: 0 divided by 7 or by -7 gives (0, 0).
  • divisor-one: 9 divided by 1 gives (9, 0).
  • int-max, int-min, min-by-max and max-by-min: the largest and the smallest 32-bit integers. The change to the result never overflows, because the remainder and b have opposite signs when it adds b.

Pitfalls

Truncated division in C

The C operators / and % round the quotient toward zero14:

This code runs but gives a wrong answer on purpose.

#include <stdio.h>

int main(void) {
    printf("%d %d\n", -17 / 5, -17 % 5);
    return 0;
}
Output
-3 -2

The floor result is (-4, 3). The integer operator / in Java, Go and Rust also rounds toward zero31719. Use the change from the Task section, or a function such as Math.floorDiv and Math.floorMod in Java3.

The comma operator in a JavaScript return

return q, r; does not return two values in JavaScript. "The comma (,) operator evaluates each of its operands (from left to right) and returns the value of the last operand."21

This code runs but gives a wrong answer on purpose.

function divMod(a, b) {
  return Math.floor(a / b), a % b;
}

console.log(divMod(17, 5));
Output
2

The function returns only the remainder. Return an array, [q, r], or an object, { quotient: q, remainder: r }.

Too many names at the unpack in Python

"Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence."5

This code runs but gives a wrong answer on purpose.

try:
    q, r, extra = divmod(17, 5)
except ValueError as e:
    print(e)
Output
not enough values to unpack (expected 3, got 2)

Use one name for each value in the tuple.

Code

The build runs the native tests of each language in a pinned toolchain.

divmod_floor.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/return-multiple-values/.


def div_mod(a: int, b: int) -> tuple[int, int]:
    """Return the quotient and the remainder of the floor division of a by b."""
    return a // b, a % b
test_divmod_floor.py 37 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/return-multiple-values/.

import pytest

from divmod_floor import div_mod

CASES = {
    "positive": (17, 5, 3, 2),
    "exact": (20, 4, 5, 0),
    "smaller-dividend": (3, 10, 0, 3),
    "negative-dividend": (-17, 5, -4, 3),
    "negative-divisor": (17, -5, -4, -3),
    "both-negative": (-17, -5, 3, -2),
    "exact-negative": (-20, 4, -5, 0),
    "small-negative": (-3, 10, -1, 7),
    "zero-dividend": (0, 7, 0, 0),
    "zero-negative-divisor": (0, -7, 0, 0),
    "divisor-one": (9, 1, 9, 0),
    "int-max": (2147483647, 2, 1073741823, 1),
    "int-min": (-2147483648, 3, -715827883, 1),
    "min-by-max": (-2147483648, 2147483647, -2, 2147483646),
    "max-by-min": (2147483647, -2147483648, -1, -1),
}


@pytest.mark.parametrize("name", CASES)
def test_div_mod(name):
    a, b, q, r = CASES[name]
    quotient, remainder = div_mod(a, b)
    assert (quotient, remainder) == (q, r)


@pytest.mark.parametrize("name", CASES)
def test_same_as_builtin_divmod(name):
    a, b, _, _ = CASES[name]
    assert div_mod(a, b) == divmod(a, b)
divmod.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

#ifndef DIVMOD_HPP
#define DIVMOD_HPP

// The two results of div_mod.
struct div_mod_result {
    int quotient;
    int remainder;
};

// Returns the quotient and the remainder of the floor division of a by b.
inline div_mod_result div_mod(int a, int b) {
    int q = a / b;
    int r = a % b;
    if (r != 0 && (r < 0) != (b < 0)) {
        q -= 1;
        r += b;
    }
    return {q, r};
}

#endif
test_divmod.cpp 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

#include <climits>
#include <cstdio>

#include "divmod.hpp"

namespace {

struct test_case {
    const char* name;
    int a, b, q, r;
};

const test_case cases[] = {
    {"positive", 17, 5, 3, 2},
    {"exact", 20, 4, 5, 0},
    {"smaller-dividend", 3, 10, 0, 3},
    {"negative-dividend", -17, 5, -4, 3},
    {"negative-divisor", 17, -5, -4, -3},
    {"both-negative", -17, -5, 3, -2},
    {"exact-negative", -20, 4, -5, 0},
    {"small-negative", -3, 10, -1, 7},
    {"zero-dividend", 0, 7, 0, 0},
    {"zero-negative-divisor", 0, -7, 0, 0},
    {"divisor-one", 9, 1, 9, 0},
    {"int-max", INT_MAX, 2, 1073741823, 1},
    {"int-min", INT_MIN, 3, -715827883, 1},
    {"min-by-max", INT_MIN, INT_MAX, -2, 2147483646},
    {"max-by-min", INT_MAX, INT_MIN, -1, -1},
};

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        const auto [quotient, remainder] = div_mod(c.a, c.b);
        if (quotient != c.q || remainder != c.r) {
            std::printf("FAIL %s: got (%d, %d)\n", c.name, quotient, remainder);
            ++failures;
        }
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
Division.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

/** Floor division that returns two results in a record. */
public final class Division {
    private Division() {}

    /** The two results of divMod. */
    public record QuotientAndRemainder(int quotient, int remainder) {}

    /** Returns the quotient and the remainder of the floor division of a by b. */
    public static QuotientAndRemainder divMod(int a, int b) {
        return new QuotientAndRemainder(Math.floorDiv(a, b), Math.floorMod(a, b));
    }
}
DivisionTest.java 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class DivisionTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("positive", 17, 5, 3, 2),
                Arguments.of("exact", 20, 4, 5, 0),
                Arguments.of("smaller-dividend", 3, 10, 0, 3),
                Arguments.of("negative-dividend", -17, 5, -4, 3),
                Arguments.of("negative-divisor", 17, -5, -4, -3),
                Arguments.of("both-negative", -17, -5, 3, -2),
                Arguments.of("exact-negative", -20, 4, -5, 0),
                Arguments.of("small-negative", -3, 10, -1, 7),
                Arguments.of("zero-dividend", 0, 7, 0, 0),
                Arguments.of("zero-negative-divisor", 0, -7, 0, 0),
                Arguments.of("divisor-one", 9, 1, 9, 0),
                Arguments.of("int-max", 2147483647, 2, 1073741823, 1),
                Arguments.of("int-min", -2147483648, 3, -715827883, 1),
                Arguments.of("min-by-max", -2147483648, 2147483647, -2, 2147483646),
                Arguments.of("max-by-min", 2147483647, -2147483648, -1, -1)
        );
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void divMod(String name, int a, int b, int q, int r) {
        Division.QuotientAndRemainder result = Division.divMod(a, b);
        assertEquals(q, result.quotient());
        assertEquals(r, result.remainder());
        assertEquals(new Division.QuotientAndRemainder(q, r), result);
    }
}
divmod.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

#include "divmod.h"

void div_mod(int a, int b, int *quotient, int *remainder) {
    // The C operators / and % truncate toward zero. Move a result that is
    // not exact one step down, so that the quotient is the floor.
    int q = a / b;
    int r = a % b;
    if (r != 0 && (r < 0) != (b < 0)) {
        q -= 1;
        r += b;
    }
    *quotient = q;
    *remainder = r;
}
divmod.h 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

#ifndef DIVMOD_H
#define DIVMOD_H

// Stores the quotient and the remainder of the floor division of a by b in
// *quotient and *remainder. b is not 0.
void div_mod(int a, int b, int *quotient, int *remainder);

#endif
test_divmod.c 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

#include "divmod.h"

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

struct test_case {
    const char *name;
    int a, b, q, r;
};

static const struct test_case cases[] = {
    {"positive", 17, 5, 3, 2},
    {"exact", 20, 4, 5, 0},
    {"smaller-dividend", 3, 10, 0, 3},
    {"negative-dividend", -17, 5, -4, 3},
    {"negative-divisor", 17, -5, -4, -3},
    {"both-negative", -17, -5, 3, -2},
    {"exact-negative", -20, 4, -5, 0},
    {"small-negative", -3, 10, -1, 7},
    {"zero-dividend", 0, 7, 0, 0},
    {"zero-negative-divisor", 0, -7, 0, 0},
    {"divisor-one", 9, 1, 9, 0},
    {"int-max", INT_MAX, 2, 1073741823, 1},
    {"int-min", INT_MIN, 3, -715827883, 1},
    {"min-by-max", INT_MIN, INT_MAX, -2, 2147483646},
    {"max-by-min", INT_MAX, INT_MIN, -1, -1},
};

int main(void) {
    int failures = 0;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        int q, r;
        div_mod(c->a, c->b, &q, &r);
        if (q != c->q || r != c->r) {
            printf("FAIL %s: got (%d, %d), want (%d, %d)\n", c->name, q, r, c->q, c->r);
            failures++;
        }
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
Division.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

/// <summary>Floor division that returns two results in a tuple.</summary>
public static class Division
{
    /// <summary>Returns the quotient and the remainder of the floor division of a by b.</summary>
    public static (int Quotient, int Remainder) DivMod(int a, int b)
    {
        int q = a / b;
        int r = a % b;
        if (r != 0 && (r < 0) != (b < 0))
        {
            q -= 1;
            r += b;
        }
        return (q, r);
    }
}
DivisionTests.cs 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

using Xunit;

public sealed class DivisionTests
{
    public static TheoryData<string, int, int, int, int> Cases => new()
    {
        { "positive", 17, 5, 3, 2 },
        { "exact", 20, 4, 5, 0 },
        { "smaller-dividend", 3, 10, 0, 3 },
        { "negative-dividend", -17, 5, -4, 3 },
        { "negative-divisor", 17, -5, -4, -3 },
        { "both-negative", -17, -5, 3, -2 },
        { "exact-negative", -20, 4, -5, 0 },
        { "small-negative", -3, 10, -1, 7 },
        { "zero-dividend", 0, 7, 0, 0 },
        { "zero-negative-divisor", 0, -7, 0, 0 },
        { "divisor-one", 9, 1, 9, 0 },
        { "int-max", 2147483647, 2, 1073741823, 1 },
        { "int-min", -2147483648, 3, -715827883, 1 },
        { "min-by-max", -2147483648, 2147483647, -2, 2147483646 },
        { "max-by-min", 2147483647, -2147483648, -1, -1 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void DivMod(string name, int a, int b, int q, int r)
    {
        Assert.NotNull(name);
        var (quotient, remainder) = Division.DivMod(a, b);
        Assert.Equal(q, quotient);
        Assert.Equal(r, remainder);
        Assert.Equal(q, Division.DivMod(a, b).Quotient);
    }
}
divmod.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

/** Returns [quotient, remainder] of the floor division of a by b. */
export function divMod(a, b) {
  let q = Math.trunc(a / b);
  let r = a % b;
  if (r !== 0 && r < 0 !== b < 0) {
    q -= 1;
    r += b;
  }
  // a / b and a % b can give -0. Adding 0 turns -0 into 0.
  return [q + 0, r + 0];
}
divmod.test.js 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { divMod } from "./divmod.js";

const cases = [
  ["positive", 17, 5, [3, 2]],
  ["exact", 20, 4, [5, 0]],
  ["smaller-dividend", 3, 10, [0, 3]],
  ["negative-dividend", -17, 5, [-4, 3]],
  ["negative-divisor", 17, -5, [-4, -3]],
  ["both-negative", -17, -5, [3, -2]],
  ["exact-negative", -20, 4, [-5, 0]],
  ["small-negative", -3, 10, [-1, 7]],
  ["zero-dividend", 0, 7, [0, 0]],
  ["zero-negative-divisor", 0, -7, [0, 0]],
  ["divisor-one", 9, 1, [9, 0]],
  ["int-max", 2147483647, 2, [1073741823, 1]],
  ["int-min", -2147483648, 3, [-715827883, 1]],
  ["min-by-max", -2147483648, 2147483647, [-2, 2147483646]],
  ["max-by-min", 2147483647, -2147483648, [-1, -1]],
];

for (const [name, a, b, want] of cases) {
  test(name, () => {
    const [quotient, remainder] = divMod(a, b);
    assert.deepEqual([quotient, remainder], want);
  });
}
divmod.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

/** Returns [quotient, remainder] of the floor division of a by b. */
export function divMod(a: number, b: number): [number, number] {
  let q = Math.trunc(a / b);
  let r = a % b;
  if (r !== 0 && r < 0 !== b < 0) {
    q -= 1;
    r += b;
  }
  // a / b and a % b can give -0. Adding 0 turns -0 into 0.
  return [q + 0, r + 0];
}
divmod.test.ts 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { divMod } from "./divmod.ts";

const cases: [string, number, number, [number, number]][] = [
  ["positive", 17, 5, [3, 2]],
  ["exact", 20, 4, [5, 0]],
  ["smaller-dividend", 3, 10, [0, 3]],
  ["negative-dividend", -17, 5, [-4, 3]],
  ["negative-divisor", 17, -5, [-4, -3]],
  ["both-negative", -17, -5, [3, -2]],
  ["exact-negative", -20, 4, [-5, 0]],
  ["small-negative", -3, 10, [-1, 7]],
  ["zero-dividend", 0, 7, [0, 0]],
  ["zero-negative-divisor", 0, -7, [0, 0]],
  ["divisor-one", 9, 1, [9, 0]],
  ["int-max", 2147483647, 2, [1073741823, 1]],
  ["int-min", -2147483648, 3, [-715827883, 1]],
  ["min-by-max", -2147483648, 2147483647, [-2, 2147483646]],
  ["max-by-min", 2147483647, -2147483648, [-1, -1]],
];

for (const [name, a, b, want] of cases) {
  test(name, () => {
    const [quotient, remainder] = divMod(a, b);
    assert.deepEqual([quotient, remainder], want);
  });
}
divmod.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

// Package divmod returns two results from one function.
package divmod

// DivMod returns the quotient and the remainder of the floor division of a by b.
func DivMod(a, b int32) (int32, int32) {
	// The Go operators / and % truncate toward zero. Move a result that is
	// not exact one step down, so that the quotient is the floor.
	q, r := a/b, a%b
	if r != 0 && (r < 0) != (b < 0) {
		q--
		r += b
	}
	return q, r
}
divmod_test.go 41 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

package divmod

import (
	"math"
	"testing"
)

var cases = []struct {
	name       string
	a, b, q, r int32
}{
	{"positive", 17, 5, 3, 2},
	{"exact", 20, 4, 5, 0},
	{"smaller-dividend", 3, 10, 0, 3},
	{"negative-dividend", -17, 5, -4, 3},
	{"negative-divisor", 17, -5, -4, -3},
	{"both-negative", -17, -5, 3, -2},
	{"exact-negative", -20, 4, -5, 0},
	{"small-negative", -3, 10, -1, 7},
	{"zero-dividend", 0, 7, 0, 0},
	{"zero-negative-divisor", 0, -7, 0, 0},
	{"divisor-one", 9, 1, 9, 0},
	{"int-max", math.MaxInt32, 2, 1073741823, 1},
	{"int-min", math.MinInt32, 3, -715827883, 1},
	{"min-by-max", math.MinInt32, math.MaxInt32, -2, 2147483646},
	{"max-by-min", math.MaxInt32, math.MinInt32, -1, -1},
}

func TestDivMod(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			q, r := DivMod(c.a, c.b)
			if q != c.q || r != c.r {
				t.Fatalf("got (%d, %d), want (%d, %d)", q, r, c.q, c.r)
			}
		})
	}
}
divmod.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

/// Returns the quotient and the remainder of the floor division of `a` by `b`.
pub fn div_mod(a: i32, b: i32) -> (i32, i32) {
    // The operators / and % truncate toward zero. Move a result that is
    // not exact one step down, so that the quotient is the floor.
    let (q, r) = (a / b, a % b);
    if r != 0 && (r < 0) != (b < 0) {
        (q - 1, r + b)
    } else {
        (q, r)
    }
}
tests/divmod_test.rs 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/return-multiple-values/.

use algo_return_multiple_values::div_mod;

const CASES: &[(&str, i32, i32, i32, i32)] = &[
    ("positive", 17, 5, 3, 2),
    ("exact", 20, 4, 5, 0),
    ("smaller-dividend", 3, 10, 0, 3),
    ("negative-dividend", -17, 5, -4, 3),
    ("negative-divisor", 17, -5, -4, -3),
    ("both-negative", -17, -5, 3, -2),
    ("exact-negative", -20, 4, -5, 0),
    ("small-negative", -3, 10, -1, 7),
    ("zero-dividend", 0, 7, 0, 0),
    ("zero-negative-divisor", 0, -7, 0, 0),
    ("divisor-one", 9, 1, 9, 0),
    ("int-max", i32::MAX, 2, 1073741823, 1),
    ("int-min", i32::MIN, 3, -715827883, 1),
    ("min-by-max", i32::MIN, i32::MAX, -2, 2147483646),
    ("max-by-min", i32::MAX, i32::MIN, -1, -1),
];

#[test]
fn cases() {
    for &(name, a, b, q, r) in CASES {
        let (quotient, remainder) = div_mod(a, b);
        assert_eq!((quotient, remainder), (q, r), "{name}");
    }
}

#[test]
fn same_as_div_euclid_for_a_positive_divisor() {
    for &(_, a, b, _, _) in CASES {
        if b > 0 {
            assert_eq!(div_mod(a, b), (a.div_euclid(b), a.rem_euclid(b)));
        }
    }
}
divmod.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/return-multiple-values/.

# div_mod A B
# Prints the quotient and the remainder of the floor division of A by B,
# with a space between them. The caller reads them with read -r.
div_mod() {
  local a=$1 b=$2
  # The operators / and % truncate toward zero. Move a result that is not
  # exact one step down, so that the quotient is the floor.
  local q=$((a / b)) r=$((a % b))
  if ((r != 0 && (r < 0) != (b < 0))); then
    ((q -= 1, r += b))
  fi
  echo "$q $r"
}
test_divmod.bats 29 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/return-multiple-values/.

setup() {
  source "$BATS_TEST_DIRNAME/divmod.sh"
}

@test "positive" { run div_mod 17 5; [ "$output" = "3 2" ]; }
@test "exact" { run div_mod 20 4; [ "$output" = "5 0" ]; }
@test "smaller-dividend" { run div_mod 3 10; [ "$output" = "0 3" ]; }
@test "negative-dividend" { run div_mod -17 5; [ "$output" = "-4 3" ]; }
@test "negative-divisor" { run div_mod 17 -5; [ "$output" = "-4 -3" ]; }
@test "both-negative" { run div_mod -17 -5; [ "$output" = "3 -2" ]; }
@test "exact-negative" { run div_mod -20 4; [ "$output" = "-5 0" ]; }
@test "small-negative" { run div_mod -3 10; [ "$output" = "-1 7" ]; }
@test "zero-dividend" { run div_mod 0 7; [ "$output" = "0 0" ]; }
@test "zero-negative-divisor" { run div_mod 0 -7; [ "$output" = "0 0" ]; }
@test "divisor-one" { run div_mod 9 1; [ "$output" = "9 0" ]; }
@test "int-max" { run div_mod 2147483647 2; [ "$output" = "1073741823 1" ]; }
@test "int-min" { run div_mod -2147483648 3; [ "$output" = "-715827883 1" ]; }
@test "min-by-max" { run div_mod -2147483648 2147483647; [ "$output" = "-2 2147483646" ]; }
@test "max-by-min" { run div_mod 2147483647 -2147483648; [ "$output" = "-1 -1" ]; }

@test "read into two variables" {
  read -r q r < <(div_mod -17 5)
  [ "$q" = "-4" ]
  [ "$r" = "3" ]
}

References

  1. Built-in Functions, The Python Standard Library, divmod()
  2. Expressions, The Python Language Reference, 6.7 Binary arithmetic operations
  3. Class Math, Java SE 25 API, floorDiv(int, int); floorMod(int, int)
  4. Modulo, Wikipedia, Variants of the definition
  5. Data Structures, The Python Tutorial, 5.3 Tuples and Sequences
  6. Destructuring, MDN Web Docs JavaScript Reference, the introduction
  7. Remainder (%), MDN Web Docs JavaScript Reference, the introduction
  8. Object Types, The TypeScript Handbook, Tuple Types
  9. Record Classes, Java Platform, Standard Edition Java Language Updates, the introduction
  10. Tuple types, C# reference, Use cases of tuples
  11. Method parameters and modifiers, C# reference, out parameter modifier
  12. Effective Go, Multiple return values
  13. div, ldiv, lldiv, imaxdiv, C reference, cppreference.com, the introduction; Notes
  14. Arithmetic operators, C reference, cppreference.com, Division
  15. Structured binding declaration, C++ reference, cppreference.com, the introduction
  16. std::pair, C++ reference, cppreference.com, the introduction
  17. The Go Programming Language Specification, Integer operators
  18. What Is Ownership?, The Rust Programming Language, Return Values and Scope
  19. Data Types, The Rust Programming Language, Numeric Operations; The Tuple Type
  20. Bash Builtin Commands, Bash Reference Manual, read
  21. Comma operator (,), MDN Web Docs JavaScript Reference, the introduction

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source