Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
math/big: GCD support for negative and zero arguments #28878
Please consider adding support for zero and negative arguments to
As of version 1.11.1, to calculate GCD of two integers one has to write:
In other words, one needs two extra allocations (or copies) as the
If on the other hand negative inputs were allowed the code would read:
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.
Note, you can avoid allocation by using:
Which switches the sign without allocation.
What would be the proposed convention for the signs of the Bezout coefficients?
I don't think there is an established convention here.
For zero values, I presume you would set
What is the use case for GCD of negative numbers?
That would mutate the arguments, however. I don't think it is desirable to change
If it worked as
Normalizing fractions, computing content of polynomials, simplify integer matrices, all these work beyond natural numbers.
Yes, it's not ideal that you would have to track the signs of
For reference, GMP uses the first convention for the Bezout coefficients