1 /* mpz_mul -- Multiply two integers.
3 Copyright 1991, 1993, 1994, 1996, 2000, 2001, 2005, 2009, 2011, 2012 Free
4 Software Foundation, Inc.
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/. */
32 #include <stdio.h> /* for NULL */
38 mpz_mul (mpz_ptr w
, mpz_srcptr u
, mpz_srcptr v
)
43 mp_size_t sign_product
;
53 sign_product
= usize
^ vsize
;
59 MPZ_SRCPTR_SWAP (u
, v
);
60 MP_SIZE_T_SWAP (usize
, vsize
);
69 #if HAVE_NATIVE_mpn_mul_2
72 wp
= MPZ_REALLOC (w
, usize
+vsize
);
74 cy_limb
= mpn_mul_1 (wp
, PTR (u
), usize
, PTR (v
)[0]);
77 cy_limb
= mpn_mul_2 (wp
, PTR (u
), usize
, PTR (v
));
81 usize
+= (cy_limb
!= 0);
82 SIZ (w
) = (sign_product
>= 0 ? usize
: -usize
);
88 wp
= MPZ_REALLOC (w
, usize
+1);
89 cy_limb
= mpn_mul_1 (wp
, PTR (u
), usize
, PTR (v
)[0]);
91 usize
+= (cy_limb
!= 0);
92 SIZ (w
) = (sign_product
>= 0 ? usize
: -usize
);
103 /* Ensure W has space enough to store the result. */
104 wsize
= usize
+ vsize
;
105 if (ALLOC (w
) < wsize
)
107 if (wp
== up
|| wp
== vp
)
110 free_me_size
= ALLOC (w
);
113 (*__gmp_free_func
) (wp
, (size_t) ALLOC (w
) * GMP_LIMB_BYTES
);
116 wp
= __GMP_ALLOCATE_FUNC_LIMBS (wsize
);
121 /* Make U and V not overlap with W. */
124 /* W and U are identical. Allocate temporary space for U. */
125 up
= TMP_ALLOC_LIMBS (usize
);
126 /* Is V identical too? Keep it identical with U. */
129 /* Copy to the temporary space. */
130 MPN_COPY (up
, wp
, usize
);
134 /* W and V are identical. Allocate temporary space for V. */
135 vp
= TMP_ALLOC_LIMBS (vsize
);
136 /* Copy to the temporary space. */
137 MPN_COPY (vp
, wp
, vsize
);
143 mpn_sqr (wp
, up
, usize
);
144 cy_limb
= wp
[wsize
- 1];
148 cy_limb
= mpn_mul (wp
, up
, usize
, vp
, vsize
);
151 wsize
-= cy_limb
== 0;
153 SIZ (w
) = sign_product
< 0 ? -wsize
: wsize
;
155 (*__gmp_free_func
) (free_me
, free_me_size
* GMP_LIMB_BYTES
);