overflow in mpz type with a simple mpz_add_ui

Vincent Lefevre vincent at vinc17.net
Mon Sep 21 23:37:25 UTC 2020

On 2020-09-21 21:17:36 +0200, Torbjorn Granlund wrote:
> Vincent Lefevre <vincent at vinc17.net> writes:
>   This is not properly documented, then. The manual says:
>        'mpz_add_ui', 'mpz_sub_ui', 'mpf_add_ui' and 'mpf_sub_ui' benefit
>        from an in-place operation like 'mpz_add_ui(x,x,y)', since usually
>                ^^^^^^^^^^^^^^^^^^
>        only one or two limbs of 'x' will need to be changed.  The same
>        applies to the full precision 'mpz_add' etc if 'y' is small.  If
>        'y' is big then cache locality may be helped, but that's all.
>   Since this should be an in-place operation (as there is no carry),
>   an overflow is unexpected here.
> Overflow here is a result of the mathmatical result.  Whether things are
> done "in place" or not is not part of it.

No, here this is not the result of the mathematical result. In my
example, this is just a consequence of GMP's implementation.

> But overflow might be flagged one limb too early for addition; instead
> of at 2^27-1 limbs for 32-bit hosts it might happen already at 2^27-2
> limbs.  I cannot say that's particularly bad.

Instead of flagging overflow before the addition, GMP should flag it
after, if it really occurs.

Vincent Lefèvre <vincent at vinc17.net> - Web: <https://www.vinc17.net/>
100% accessible validated (X)HTML - Blog: <https://www.vinc17.net/blog/>
Work: CR INRIA - computer arithmetic / AriC project (LIP, ENS-Lyon)

More information about the gmp-bugs mailing list