Taskintro
Detect division by zero
Also called division by zero, ZeroDivisionError, ArithmeticException, DivideByZeroException, checked_div, Math.divideExact, safe division, integer division error.
Divide two integers and report a zero divisor instead of a crash. Integer division by zero is an error, an exception or undefined behavior; float division by zero gives infinity or NaN.
- Evidence
- Code in 10 languages
Task
Divide two 64-bit signed integers, and round the quotient toward zero. When the divisor is zero, report it, and do not crash or return a wrong value.
The function safe_div(a, b) returns the quotient, or no value. For example, safe_div(7, 2) is 3, safe_div(-7, 2) is -3, and safe_div(5, 0) has no value.
There is a second case with no valid result. The smallest 64-bit value, -9223372036854775808, divided by -1 is 9223372036854775808, which is one more than the largest 64-bit value. So the function also returns no value for this case. See Detect integer overflow for the other overflows.
Each language treats an integer division by zero in its own way:
- An error or an exception. Python raises
ZeroDivisionError, Java throwsArithmeticException, C# throwsDivideByZeroException, Go panics, Rust panics, and Bash stops the expression with an error. - Undefined behavior. In C and C++ the program has no defined result.
- No error. A JavaScript
numberis a float, so5 / 0isInfinity.
The safe way is the same in each language: test the divisor before the division.
Solutions
| Language | Check | 5 / 0 on integers |
MIN / -1 |
|---|---|---|---|
| Python | test b == 0 |
ZeroDivisionError |
exact, no error |
| JavaScript, TypeScript | test b === 0n on BigInt values |
RangeError |
exact, no error |
| Java | Math.divideExact |
ArithmeticException |
MIN, no error |
| C, C++ | test both cases before the division | undefined behavior | undefined behavior |
| C# | catch ArithmeticException |
DivideByZeroException |
ArithmeticException |
| Go | test both cases before the division | run-time panic | MIN, no error |
| Rust | i64::checked_div |
panic | panic |
| Bash | test both cases before the division | an error | no check for overflow |
- Python.
ZeroDivisionErroris "Raised when the second argument of a division or modulo operation is zero"1. The operator//does not round toward zero: "The result is always rounded towards minus infinity"2. So the solution divides the magnitudes and sets the sign after. A Pythoninthas no fixed width, so the solution also compares the quotient with the 64-bit range. - JavaScript. The solution uses
BigIntvalues. ForBigIntoperands, the result is "the quotient of the two operands truncated towards zero", and "A RangeError is thrown if the divisor y is 0n"3.BigInt.asIntN(64, q)changesqonly when it does not fit in 64 bits4. - TypeScript. The same code as JavaScript, with the type
bigint. - Java. When "the value of the divisor in an integer division is 0", the plain
/throws: "then an ArithmeticException is thrown"5. For the smallest value divided by -1, "integer overflow occurs and the result is equal to the dividend", and "Despite the overflow, no exception is thrown in this case."5Math.divideExactthrows in both cases; the overflow "occurs in this method if x is Long.MIN_VALUE and y is -1"6. - C. "If the second operand is zero, the behavior is undefined."7 Also, "If the quotient a/b is not representable in the result type, the behavior of both a/b and a%b is undefined"7. The solution tests both cases before the division.
- C++. The same test as C, in a
constexprfunction that returnsstd::optional<std::int64_t>. - C#. "Integer division by zero always throws a DivideByZeroException."8 For the smallest value divided by -1, "The .NET runtime throws an ArithmeticException in this case"8, even in an unchecked context.
DivideByZeroExceptionis a kind ofArithmeticException, so the solution catchesArithmeticExceptionand returnsnull. - Go. "If the divisor is zero at run time, a run-time panic occurs."9 The smallest value divided by -1 does not panic: the spec says that
x / -1"is equal to x"9 for the most negative valuex. The solution tests both cases before the division. - Rust.
checked_div"Computes self / rhs" and returnsNone"if rhs == 0 or the division results in overflow"10. - Bash. Bash arithmetic has "no check for overflow, though division by 0 is trapped and flagged as an error"11. The error stops the expansion, so the solution tests the divisor first and returns status 1.
The Python function, and the floor division that it does not use:
INT64_MIN, INT64_MAX = -(2**63), 2**63 - 1
def safe_div(a, b):
if b == 0:
return None
q = abs(a) // abs(b)
if (a < 0) != (b < 0):
q = -q
return q if INT64_MIN <= q <= INT64_MAX else None
print(safe_div(7, 2), safe_div(-7, 2), safe_div(5, 0))
print(safe_div(INT64_MIN, -1))
print(-7 // 2)
try:
5 // 0
except ZeroDivisionError as e:
print(type(e).__name__ + ":", e)
3 -3 None
None
-4
ZeroDivisionError: integer division or modulo by zero
In Java, the plain operator and Math.divideExact differ only in the overflow case:
public class Main {
public static void main(String[] args) {
long min = Long.MIN_VALUE;
long minusOne = -1;
long zero = 0;
System.out.println(min / minusOne);
try {
System.out.println(Math.divideExact(min, minusOne));
} catch (ArithmeticException e) {
System.out.println("divideExact: " + e.getMessage());
}
try {
System.out.println(5 / zero);
} catch (ArithmeticException e) {
System.out.println("/: " + e.getMessage());
}
}
}
-9223372036854775808
divideExact: long overflow
/: / by zero
In Go, a zero divisor at run time panics, and the program can recover from the panic:
package main
import (
"fmt"
"math"
)
func divide(a, b int64) (q int64, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
}
}()
return a / b, nil
}
func main() {
fmt.Println(divide(7, 2))
fmt.Println(divide(5, 0))
fmt.Println(divide(math.MinInt64, -1))
}
3 <nil>
0 runtime error: integer divide by zero
-9223372036854775808 <nil>
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
exact,remainder-dropped,zero-dividend: ordinary quotients. Zero divided by a number is 0.zero-divisor,negative-by-zero: a zero divisor gives no value, for each sign of the dividend.zero-by-zero: 0 divided by 0 gives no value too.negative-dividend,negative-divisor,both-negative: the quotient rounds toward zero, so -7 divided by 2 is -3, not -4.min-by-minus-one: the quotient does not fit in 64 bits.min-by-one,max-by-minus-one,min-by-max: other quotients at the limits, which fit.
Pitfalls
- Float division by zero is not an error in most languages. It follows IEEE 754 (see NaN and infinity): a nonzero number divided by zero gives an infinity, and 0 divided by 0 gives NaN. In JavaScript, "number division by zero returns Infinity or -Infinity"3. In C#, "Arithmetic operations by using the float and double types never throw an exception"8. In Go, "The result of a floating-point or complex division by zero is not specified beyond the IEEE 754 standard"9. So a test for an exception does not find these results; test the divisor, or test the result with
isFiniteorisNaN:
This code runs but gives a wrong answer on purpose.
console.log(5 / 0, -5 / 0, 0 / 0);
console.log(Number.isFinite(5 / 0));
console.log(1 / 1e-320);
try {
console.log(5n / 0n);
} catch (e) {
console.log(e.name);
}
Infinity -Infinity NaN
false
Infinity
RangeError
- Python float division by zero raises. Python does not follow the IEEE 754 default here:
1.0 / 0.0raisesZeroDivisionError, like the integer division1. Code that moves between Python and another language must handle both results.
This code runs but gives a wrong answer on purpose.
for a, b in [(1, 0), (1.0, 0.0), (0.0, 0.0)]:
try:
print(a / b)
except ZeroDivisionError as e:
print(type(e).__name__ + ":", e)
ZeroDivisionError: division by zero
ZeroDivisionError: float division by zero
ZeroDivisionError: float division by zero
-
A divisor near zero can overflow. A test for zero does not cover a float divisor that is very small. In JavaScript,
1 / 1e-320isInfinity, because the quotient is larger than the largest float. Test the result too, when the divisor comes from a computation. -
The remainder has the same problem.
a % 0is a division by zero in each language above, and in CINT_MIN % -1is undefined behavior7. Test the divisor before a remainder too. -
A test after a crash is too late in C. In C and C++, a division by zero has no defined result7. The program can stop, print a wrong value or go on, and a compiler can remove a test that comes after the division. Only a test before the division is safe.
Related tasks
- Detect integer overflow: the other error of integer arithmetic.
- Do integer arithmetic: the division and remainder operators of each language.
- Compare floating-point numbers: NaN and infinity in comparisons.
See also the concepts Integer division and modulo, NaN and infinity and Integer overflow behaviour.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/detect-division-by-zero/.
INT64_MIN = -(2**63)
INT64_MAX = 2**63 - 1
def safe_div(a: int, b: int) -> int | None:
"""Returns a / b rounded toward zero, or None for a zero divisor or a
quotient that does not fit in 64 signed bits."""
if b == 0:
return None # a // 0 raises ZeroDivisionError
# // rounds toward minus infinity, so divide the magnitudes and set the
# sign after, to round toward zero.
q = abs(a) // abs(b)
if (a < 0) != (b < 0):
q = -q
return q if INT64_MIN <= q <= INT64_MAX else None
test_safe_div.py 33 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/detect-division-by-zero/.
import pytest
from safe_div import INT64_MAX, INT64_MIN, safe_div
CASES = {
"exact": (12, 4, 3),
"remainder-dropped": (7, 2, 3),
"zero-dividend": (0, 5, 0),
"zero-divisor": (5, 0, None),
"negative-by-zero": (-5, 0, None),
"zero-by-zero": (0, 0, None),
"negative-dividend": (-7, 2, -3),
"negative-divisor": (7, -2, -3),
"both-negative": (-7, -2, 3),
"min-by-minus-one": (INT64_MIN, -1, None),
"min-by-one": (INT64_MIN, 1, INT64_MIN),
"max-by-minus-one": (INT64_MAX, -1, -INT64_MAX),
"min-by-max": (INT64_MIN, INT64_MAX, -1),
}
@pytest.mark.parametrize("case", CASES)
def test_safe_div(case):
a, b, want = CASES[case]
assert safe_div(a, b) == want
def test_floor_division_differs():
assert -7 // 2 == -4
with pytest.raises(ZeroDivisionError):
5 // 0
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
#pragma once
#include <cstdint>
#include <limits>
#include <optional>
// safe_div returns a / b rounded toward zero, or nothing when b is 0 or when
// the quotient does not fit in std::int64_t. Both cases are undefined
// behavior, so the function tests them before the division.
constexpr std::optional<std::int64_t> safe_div(std::int64_t a, std::int64_t b) {
if (b == 0 || (a == std::numeric_limits<std::int64_t>::min() && b == -1)) {
return std::nullopt;
}
return a / b;
}
test_safe_div.cpp 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
#include "safe_div.hpp"
#include <cstdio>
namespace {
constexpr auto MAX = std::numeric_limits<std::int64_t>::max();
constexpr auto MIN = std::numeric_limits<std::int64_t>::min();
static_assert(safe_div(7, 2) == 3);
static_assert(!safe_div(7, 0).has_value());
int failures = 0;
void check(const char *label, std::int64_t a, std::int64_t b, std::optional<std::int64_t> want) {
if (safe_div(a, b) != want) {
std::fprintf(stderr, "case %s failed\n", label);
failures++;
}
}
} // namespace
int main() {
check("exact", 12, 4, 3);
check("remainder-dropped", 7, 2, 3);
check("zero-dividend", 0, 5, 0);
check("zero-divisor", 5, 0, std::nullopt);
check("negative-by-zero", -5, 0, std::nullopt);
check("zero-by-zero", 0, 0, std::nullopt);
check("negative-dividend", -7, 2, -3);
check("negative-divisor", 7, -2, -3);
check("both-negative", -7, -2, 3);
check("min-by-minus-one", MIN, -1, std::nullopt);
check("min-by-one", MIN, 1, MIN);
check("max-by-minus-one", MAX, -1, -MAX);
check("min-by-max", MIN, MAX, -1);
if (failures > 0) {
return 1;
}
std::printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
import java.util.OptionalLong;
final class SafeDiv {
private SafeDiv() {}
/**
* Returns a / b rounded toward zero, or an empty OptionalLong for a zero divisor or a quotient
* that does not fit in a long.
*/
static OptionalLong safeDiv(long a, long b) {
try {
// a / b throws ArithmeticException when b is 0, but Long.MIN_VALUE / -1 gives
// Long.MIN_VALUE with no exception. Math.divideExact throws in both cases.
return OptionalLong.of(Math.divideExact(a, b));
} catch (ArithmeticException e) {
return OptionalLong.empty();
}
}
}
SafeDivTest.java 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.OptionalLong;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class SafeDivTest {
static final long MAX = Long.MAX_VALUE;
static final long MIN = Long.MIN_VALUE;
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("exact", 12L, 4L, OptionalLong.of(3)),
Arguments.of("remainder-dropped", 7L, 2L, OptionalLong.of(3)),
Arguments.of("zero-dividend", 0L, 5L, OptionalLong.of(0)),
Arguments.of("zero-divisor", 5L, 0L, OptionalLong.empty()),
Arguments.of("negative-by-zero", -5L, 0L, OptionalLong.empty()),
Arguments.of("zero-by-zero", 0L, 0L, OptionalLong.empty()),
Arguments.of("negative-dividend", -7L, 2L, OptionalLong.of(-3)),
Arguments.of("negative-divisor", 7L, -2L, OptionalLong.of(-3)),
Arguments.of("both-negative", -7L, -2L, OptionalLong.of(3)),
Arguments.of("min-by-minus-one", MIN, -1L, OptionalLong.empty()),
Arguments.of("min-by-one", MIN, 1L, OptionalLong.of(MIN)),
Arguments.of("max-by-minus-one", MAX, -1L, OptionalLong.of(-MAX)),
Arguments.of("min-by-max", MIN, MAX, OptionalLong.of(-1)));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void safeDiv(String name, long a, long b, OptionalLong want) {
assertEquals(want, SafeDiv.safeDiv(a, b), name);
}
@Test
void plainDivision() {
long zero = 0;
assertThrows(ArithmeticException.class, () -> System.out.println(5L / zero));
long minusOne = -1;
assertEquals(MIN, MIN / minusOne);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
#include "safe_div.h"
bool safe_div(int64_t a, int64_t b, int64_t *out) {
// Both cases are undefined behavior in C, so test them before the
// division.
if (b == 0 || (a == INT64_MIN && b == -1)) {
return false;
}
*out = a / b; // C rounds the quotient toward zero
return true;
}
safe_div.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
#ifndef SAFE_DIV_H
#define SAFE_DIV_H
#include <stdbool.h>
#include <stdint.h>
// safe_div stores a / b, rounded toward zero, in *out and returns true. It
// returns false when b is 0 or when the quotient does not fit in int64_t.
bool safe_div(int64_t a, int64_t b, int64_t *out);
#endif
test_safe_div.c 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
#include "safe_div.h"
#include <stdio.h>
static int failures = 0;
static void check(const char *label, int64_t a, int64_t b, bool want_ok, int64_t want) {
int64_t got = 0;
bool ok = safe_div(a, b, &got);
if (ok != want_ok || (ok && got != want)) {
fprintf(stderr, "case %s failed\n", label);
failures++;
}
}
int main(void) {
check("exact", 12, 4, true, 3);
check("remainder-dropped", 7, 2, true, 3);
check("zero-dividend", 0, 5, true, 0);
check("zero-divisor", 5, 0, false, 0);
check("negative-by-zero", -5, 0, false, 0);
check("zero-by-zero", 0, 0, false, 0);
check("negative-dividend", -7, 2, true, -3);
check("negative-divisor", 7, -2, true, -3);
check("both-negative", -7, -2, true, 3);
check("min-by-minus-one", INT64_MIN, -1, false, 0);
check("min-by-one", INT64_MIN, 1, true, INT64_MIN);
check("max-by-minus-one", INT64_MAX, -1, true, -INT64_MAX);
check("min-by-max", INT64_MIN, INT64_MAX, true, -1);
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
using System;
public static class Division
{
// Returns a / b rounded toward zero, or null for a zero divisor or a
// quotient that does not fit in a long. Integer division by zero throws
// DivideByZeroException, and long.MinValue / -1 throws an
// ArithmeticException, even in an unchecked context. Catch both.
public static long? SafeDiv(long a, long b)
{
try
{
return a / b;
}
catch (ArithmeticException)
{
return null;
}
}
}
SafeDivTests.cs 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
using System;
using Xunit;
public sealed class SafeDivTests
{
private const long Max = long.MaxValue;
private const long Min = long.MinValue;
public static TheoryData<string, long, long, long?> Cases => new()
{
{ "exact", 12, 4, 3 },
{ "remainder-dropped", 7, 2, 3 },
{ "zero-dividend", 0, 5, 0 },
{ "zero-divisor", 5, 0, null },
{ "negative-by-zero", -5, 0, null },
{ "zero-by-zero", 0, 0, null },
{ "negative-dividend", -7, 2, -3 },
{ "negative-divisor", 7, -2, -3 },
{ "both-negative", -7, -2, 3 },
{ "min-by-minus-one", Min, -1, null },
{ "min-by-one", Min, 1, Min },
{ "max-by-minus-one", Max, -1, -Max },
{ "min-by-max", Min, Max, -1 },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, long a, long b, long? want)
{
Assert.NotNull(name);
Assert.Equal(want, Division.SafeDiv(a, b));
}
[Fact]
public void ZeroDivisorThrows()
{
long zero = 0;
Assert.Throws<DivideByZeroException>(() => 5 / zero);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
// 64-bit values are BigInt values. BigInt division rounds toward zero, and a
// zero divisor throws a RangeError, so test the divisor first. The quotient
// of the smallest 64-bit value by -1 is 2 ** 63, which does not fit in 64
// bits; BigInt.asIntN(64, q) changes q only in that case.
export function safeDiv(a, b) {
if (b === 0n) return null;
const q = a / b;
return BigInt.asIntN(64, q) === q ? q : null;
}
safe_div.test.js 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { safeDiv } from "./safe_div.js";
const MAX = 9223372036854775807n;
const MIN = -9223372036854775808n;
const cases = [
["exact", 12n, 4n, 3n],
["remainder-dropped", 7n, 2n, 3n],
["zero-dividend", 0n, 5n, 0n],
["zero-divisor", 5n, 0n, null],
["negative-by-zero", -5n, 0n, null],
["zero-by-zero", 0n, 0n, null],
["negative-dividend", -7n, 2n, -3n],
["negative-divisor", 7n, -2n, -3n],
["both-negative", -7n, -2n, 3n],
["min-by-minus-one", MIN, -1n, null],
["min-by-one", MIN, 1n, MIN],
["max-by-minus-one", MAX, -1n, -MAX],
["min-by-max", MIN, MAX, -1n],
];
for (const [name, a, b, want] of cases) {
test(name, () => {
assert.equal(safeDiv(a, b), want);
});
}
test("BigInt division by zero throws, number division does not", () => {
assert.throws(() => 5n / 0n, RangeError);
assert.equal(5 / 0, Infinity);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
// 64-bit values are bigint values. bigint division rounds toward zero, and a
// zero divisor throws a RangeError, so test the divisor first.
export function safeDiv(a: bigint, b: bigint): bigint | null {
if (b === 0n) return null;
const q = a / b;
return BigInt.asIntN(64, q) === q ? q : null;
}
safe_div.test.ts 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { safeDiv } from "./safe_div.ts";
const MAX = 9223372036854775807n;
const MIN = -9223372036854775808n;
const cases: [string, bigint, bigint, bigint | null][] = [
["exact", 12n, 4n, 3n],
["remainder-dropped", 7n, 2n, 3n],
["zero-dividend", 0n, 5n, 0n],
["zero-divisor", 5n, 0n, null],
["negative-by-zero", -5n, 0n, null],
["zero-by-zero", 0n, 0n, null],
["negative-dividend", -7n, 2n, -3n],
["negative-divisor", 7n, -2n, -3n],
["both-negative", -7n, -2n, 3n],
["min-by-minus-one", MIN, -1n, null],
["min-by-one", MIN, 1n, MIN],
["max-by-minus-one", MAX, -1n, -MAX],
["min-by-max", MIN, MAX, -1n],
];
for (const [name, a, b, want] of cases) {
test(name, () => {
assert.equal(safeDiv(a, b), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
// Package division divides two int64 values and reports a zero divisor.
package division
import "math"
// SafeDiv returns a / b rounded toward zero and true. It returns 0 and false
// when b is 0, and when a is math.MinInt64 and b is -1.
func SafeDiv(a, b int64) (int64, bool) {
// A zero divisor at run time causes a panic. math.MinInt64 / -1 does not
// panic: the quotient wraps to math.MinInt64. So test both first.
if b == 0 || (a == math.MinInt64 && b == -1) {
return 0, false
}
return a / b, true
}
safe_div_test.go 54 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
package division
import (
"math"
"testing"
)
const (
max = math.MaxInt64
min = math.MinInt64
)
var cases = []struct {
name string
a, b int64
want int64
wantOK bool
}{
{"exact", 12, 4, 3, true},
{"remainder-dropped", 7, 2, 3, true},
{"zero-dividend", 0, 5, 0, true},
{"zero-divisor", 5, 0, 0, false},
{"negative-by-zero", -5, 0, 0, false},
{"zero-by-zero", 0, 0, 0, false},
{"negative-dividend", -7, 2, -3, true},
{"negative-divisor", 7, -2, -3, true},
{"both-negative", -7, -2, 3, true},
{"min-by-minus-one", min, -1, 0, false},
{"min-by-one", min, 1, min, true},
{"max-by-minus-one", max, -1, -max, true},
{"min-by-max", min, max, -1, true},
}
func TestSafeDiv(t *testing.T) {
for _, c := range cases {
got, ok := SafeDiv(c.a, c.b)
if got != c.want || ok != c.wantOK {
t.Errorf("%s: got (%d, %v), want (%d, %v)", c.name, got, ok, c.want, c.wantOK)
}
}
}
func TestZeroDivisorPanics(t *testing.T) {
defer func() {
if recover() == nil {
t.Error("no panic")
}
}()
var zero int64
_ = int64(5) / zero
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
/// Returns a / b rounded toward zero, or None when b is 0 or when the
/// quotient does not fit in an i64.
pub fn safe_div(a: i64, b: i64) -> Option<i64> {
// a / b panics in both cases. checked_div returns None instead.
a.checked_div(b)
}
tests/safe_div_test.rs 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/detect-division-by-zero/.
use algo_detect_division_by_zero::safe_div;
const MAX: i64 = i64::MAX;
const MIN: i64 = i64::MIN;
#[test]
fn cases() {
let cases: Vec<(&str, i64, i64, Option<i64>)> = vec![
("exact", 12, 4, Some(3)),
("remainder-dropped", 7, 2, Some(3)),
("zero-dividend", 0, 5, Some(0)),
("zero-divisor", 5, 0, None),
("negative-by-zero", -5, 0, None),
("zero-by-zero", 0, 0, None),
("negative-dividend", -7, 2, Some(-3)),
("negative-divisor", 7, -2, Some(-3)),
("both-negative", -7, -2, Some(3)),
("min-by-minus-one", MIN, -1, None),
("min-by-one", MIN, 1, Some(MIN)),
("max-by-minus-one", MAX, -1, Some(-MAX)),
("min-by-max", MIN, MAX, Some(-1)),
];
for (name, a, b, want) in cases {
assert_eq!(safe_div(a, b), want, "case {name}");
}
}
#[test]
fn float_division_by_zero() {
let zero = 0.0_f64;
assert_eq!(1.0 / zero, f64::INFINITY);
assert!((zero / zero).is_nan());
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/detect-division-by-zero/.
# Bash traps an integer division by zero as an error, and the error stops the
# arithmetic expansion. Test the divisor first, so the function can return a
# status instead.
INT64_MIN=$((-9223372036854775807 - 1))
# safe_div A B
# Prints A / B rounded toward zero, or prints nothing and returns status 1
# when B is 0 or the quotient does not fit in 64 bits.
safe_div() {
local a=$1 b=$2
if ((b == 0)) || ((a == INT64_MIN && b == -1)); then
return 1
fi
echo $((a / b))
}
test_safe_div.bats 38 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/detect-division-by-zero/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/safe_div.sh"
}
check() { # check WANT A B; WANT is none for no result
local want=$1 got status=0
shift
got=$(safe_div "$@") || status=$?
if [ "$want" = none ]; then
[ "$status" -ne 0 ] && [ -z "$got" ] || { printf 'got: %s\n' "$got"; return 1; }
else
[ "$status" -eq 0 ] && [ "$got" = "$want" ] || { printf 'got: %s\nwant: %s\n' "$got" "$want"; return 1; }
fi
}
@test "exact" { check 3 12 4; }
@test "remainder-dropped" { check 3 7 2; }
@test "zero-dividend" { check 0 0 5; }
@test "zero-divisor" { check none 5 0; }
@test "negative-by-zero" { check none -5 0; }
@test "zero-by-zero" { check none 0 0; }
@test "negative-dividend" { check -3 -7 2; }
@test "negative-divisor" { check -3 7 -2; }
@test "both-negative" { check 3 -7 -2; }
@test "min-by-minus-one" { check none -9223372036854775808 -1; }
@test "min-by-one" { check -9223372036854775808 -9223372036854775808 1; }
@test "max-by-minus-one" { check -9223372036854775807 9223372036854775807 -1; }
@test "min-by-max" { check -1 -9223372036854775808 9223372036854775807; }
@test "plain division by zero is an error" {
run -1 bash -c 'echo $((5 / 0))'
[[ "$output" == *"division by 0"* ]]
}
References
- Built-in Exceptions, Python 3 documentation, ZeroDivisionError
- Built-in Types, Python 3 documentation, Numeric Types, int, float, complex, note 1
- Division (/), MDN Web Docs, Description; Examples
- BigInt.asIntN(), MDN Web Docs, Description
- The Java Language Specification, Java SE 27 Edition, Chapter 15: Expressions, 15.17.2 Division Operator /
- Math, Java SE 27 API, divideExact(long, long)
- Arithmetic operators, C reference, cppreference.com, Multiplicative operators; Division
- Arithmetic operators, C# reference, Microsoft Learn, Division operator /; Arithmetic overflow and division by zero
- The Go Programming Language Specification, Integer operators; Floating-point operators
- i64, Rust standard library, checked_div
- Bash Reference Manual, version 5.3, 6.5 Shell Arithmetic
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag A3QDBQ Edit this page History Report an error Markdown