1 /* mpz_add, mpz_sub -- add or subtract integers.
3 Copyright 1991, 1993, 1994, 1996, 2000, 2001, 2011, 2012 Free Software
6 This file is part of the GNU MP Library.
8 The GNU MP Library is free software; you can redistribute it and/or modify
9 it under the terms of either:
11 * the GNU Lesser General Public License as published by the Free
12 Software Foundation; either version 3 of the License, or (at your
13 option) any later version.
17 * the GNU General Public License as published by the Free Software
18 Foundation; either version 2 of the License, or (at your option) any
21 or both in parallel, as here.
23 The GNU MP Library is distributed in the hope that it will be useful, but
24 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
25 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
28 You should have received copies of the GNU General Public License and the
29 GNU Lesser General Public License along with the GNU MP Library. If not,
30 see https://www.gnu.org/licenses/. */
37 #define FUNCTION mpz_add
41 #define FUNCTION mpz_sub
46 Error
, need OPERATION_add
or OPERATION_sub
51 FUNCTION (mpz_ptr w
, mpz_srcptr u
, mpz_srcptr v
)
55 mp_size_t usize
, vsize
, wsize
;
60 vsize
= VARIATION
SIZ(v
);
61 abs_usize
= ABS (usize
);
62 abs_vsize
= ABS (vsize
);
64 if (abs_usize
< abs_vsize
)
67 MPZ_SRCPTR_SWAP (u
, v
);
68 MP_SIZE_T_SWAP (usize
, vsize
);
69 MP_SIZE_T_SWAP (abs_usize
, abs_vsize
);
72 /* True: ABS_USIZE >= ABS_VSIZE. */
74 /* If not space for w (and possible carry), increase space. */
75 wsize
= abs_usize
+ 1;
76 wp
= MPZ_REALLOC (w
, wsize
);
78 /* These must be after realloc (u or v may be the same as w). */
82 if ((usize
^ vsize
) < 0)
84 /* U and V have different sign. Need to compare them to determine
85 which operand to subtract from which. */
87 /* This test is right since ABS_USIZE >= ABS_VSIZE. */
88 if (abs_usize
!= abs_vsize
)
90 mpn_sub (wp
, up
, abs_usize
, vp
, abs_vsize
);
92 MPN_NORMALIZE (wp
, wsize
);
96 else if (mpn_cmp (up
, vp
, abs_usize
) < 0)
98 mpn_sub_n (wp
, vp
, up
, abs_usize
);
100 MPN_NORMALIZE (wp
, wsize
);
106 mpn_sub_n (wp
, up
, vp
, abs_usize
);
108 MPN_NORMALIZE (wp
, wsize
);
115 /* U and V have same sign. Add them. */
116 mp_limb_t cy_limb
= mpn_add (wp
, up
, abs_usize
, vp
, abs_vsize
);
117 wp
[abs_usize
] = cy_limb
;
118 wsize
= abs_usize
+ cy_limb
;