Skip to content

math/big: GCD support for negative and zero arguments #28878

@TuomLarsen

Description

@TuomLarsen

Please consider adding support for zero and negative arguments to math/big GCD.

As of version 1.11.1, to calculate GCD of two integers one has to write:

new(big.Int).GCD(nil, nil, new(big.Int).Abs(a), new(big.Int).Abs(b))

In other words, one needs two extra allocations (or copies) as the nat field of big.Int is private.

If on the other hand negative inputs were allowed the code would read:

new(big.Int).GCD(nil, nil, a, b)

For negative inputs the resulting GCD could be treated as GCD(|a|, |b|), the precise sign does not really matter as long as it is documented. (For example, "GCD is non-negative".)

While I'm at it, it would be also nice to support zero arguments as it is well defined (GCD(a, 0) = |a|, GCD(0, 0) = 0) and it would simplify the code because there would be no need to special-case zero inputs. Currently it sets the result to zero.

Metadata

Metadata

Assignees

No one assigned

    Labels

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

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions