beta-0.89.2
[luatex.git] / source / libs / gmp / gmp-src / mpz / rootrem.c
blobac4a1e030af80ecffe505793f8fe258839a0680f
1 /* mpz_rootrem(root, rem, u, nth) -- Set ROOT to trunc(U^(1/nth)) and
2 set REM to the remainder.
4 Copyright 1999-2003, 2005, 2012 Free 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
19 later version.
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
26 for more details.
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 */
33 #include "gmp.h"
34 #include "gmp-impl.h"
36 void
37 mpz_rootrem (mpz_ptr root, mpz_ptr rem, mpz_srcptr u, unsigned long int nth)
39 mp_ptr rootp, up, remp;
40 mp_size_t us, un, rootn, remn;
41 TMP_DECL;
43 us = SIZ(u);
45 /* even roots of negatives provoke an exception */
46 if (UNLIKELY (us < 0 && (nth & 1) == 0))
47 SQRT_OF_NEGATIVE;
49 /* root extraction interpreted as c^(1/nth) means a zeroth root should
50 provoke a divide by zero, do this even if c==0 */
51 if (UNLIKELY (nth == 0))
52 DIVIDE_BY_ZERO;
54 if (us == 0)
56 if (root != NULL)
57 SIZ(root) = 0;
58 SIZ(rem) = 0;
59 return;
62 un = ABS (us);
63 rootn = (un - 1) / nth + 1;
65 TMP_MARK;
67 /* FIXME: Perhaps disallow root == NULL */
68 if (root != NULL && u != root)
69 rootp = MPZ_REALLOC (root, rootn);
70 else
71 rootp = TMP_ALLOC_LIMBS (rootn);
73 if (u != rem)
74 remp = MPZ_REALLOC (rem, un);
75 else
76 remp = TMP_ALLOC_LIMBS (un);
78 up = PTR(u);
80 if (nth == 1)
82 MPN_COPY (rootp, up, un);
83 remn = 0;
85 else
87 remn = mpn_rootrem (rootp, remp, up, un, (mp_limb_t) nth);
90 if (root != NULL)
92 SIZ(root) = us >= 0 ? rootn : -rootn;
93 if (u == root)
94 MPN_COPY (up, rootp, rootn);
97 if (u == rem)
98 MPN_COPY (up, remp, remn);
99 SIZ(rem) = us >= 0 ? remn : -remn;
100 TMP_FREE;