Skip to content

math/big: ModInverse with modulus zero is undefined #47606

@FiloSottile

Description

@FiloSottile

ModInverse is defined for all values of g, and for positive and negative values n, but not for a zero n.

ModInverse sets z to the multiplicative inverse of g in the ring ℤ/nℤ
and returns z. If g and n are not relatively prime, g has no multiplicative
inverse in the ring ℤ/nℤ. In this case, z is unchanged and the return value
is nil.

The ring of numbers modulo zero does not exist, and being coprime with zero is meaningless, so the current docs don't cover it.

Arguably, ModInverse should always panic when the modulo is zero, but currently it returns nil for g > 1, returns 1 for g = 1, returns nil for g = 0, and panics for g < 0. Turning a non-panic into a panic for the sake of consistency is asking for trouble, so we should just make it return nil consistently for n = 0.

This could break programs that try to dereference the return value of ModInverse(1, 0), but that feels like a specific enough condition that programs won't have come to rely on it #famouslastwords.

Metadata

Metadata

Labels

NeedsFixThe path to resolution is known, but the work has not been done.

Type

No type

Projects

Status

No status

Relationships

None yet

Development

No branches or pull requests

Issue actions