Skip to content

div/mod behaviour #90

@konsumlamm

Description

@konsumlamm

The behaviour of div and mod is currently inconsistent with the respective operators for ints. For example:

import bigints

func divmod(a, b: int): tuple[q, r: int] =
    (q: a div b, r: a mod b)

echo "int:"
echo "  divmod(1, 2): ", divmod(1, 2)
echo "  divmod(1, -2): ", divmod(1, -2)
echo "  divmod(-1, 2): ", divmod(-1, 2)
echo "  divmod(-1, -2): ", divmod(-1, -2)
echo "BigInt:"
echo "  divmod(1, 2): ", divmod(1'bi, 2'bi)
echo "  divmod(1, -2): ", divmod(1'bi, -2'bi)
echo "  divmod(-1, 2): ", divmod(-1'bi, 2'bi)
echo "  divmod(-1, -2): ", divmod(-1'bi, -2'bi)

prints the following:

int:
  divmod(1, 2): (q: 0, r: 1)
  divmod(1, -2): (q: 0, r: 1)
  divmod(-1, 2): (q: 0, r: -1)
  divmod(-1, -2): (q: 0, r: -1)
BigInt:
  divmod(1, 2): (q: 0, r: 1)
  divmod(1, -2): (q: -1, r: -1)
  divmod(-1, 2): (q: -1, r: 1)
  divmod(-1, -2): (q: 0, r: -1)

For ints, division rounds towards 0 and the sign of a mod b is the sign of a. Meanwhile, for BigInts, division rounds towards negative infinity and the sign of a mod b is the sign of b.

I suggest we change the behavior of BigInts to match that of ints.

@def- since you implemented this, did you have a specific reason for implementing it this way?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions