1 /* mpz_rootrem(root, rem, u, nth) -- Set ROOT to floor(U^(1/nth)) and 2 set REM to the remainder. 3 4 Copyright 1999, 2000, 2001, 2002, 2003, 2005 Free Software Foundation, Inc. 5 6 This file is part of the GNU MP Library. 7 8 The GNU MP Library is free software; you can redistribute it and/or modify 9 it under the terms of the GNU Lesser General Public License as published by 10 the Free Software Foundation; either version 3 of the License, or (at your 11 option) any later version. 12 13 The GNU MP Library is distributed in the hope that it will be useful, but 14 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 15 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 16 License for more details. 17 18 You should have received a copy of the GNU Lesser General Public License 19 along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */ 20 21 #include <stdio.h> /* for NULL */ 22 #include "gmp.h" 23 #include "gmp-impl.h" 24 25 void 26 mpz_rootrem (mpz_ptr root, mpz_ptr rem, mpz_srcptr u, unsigned long int nth) 27 { 28 mp_ptr rootp, up, remp; 29 mp_size_t us, un, rootn, remn; 30 TMP_DECL; 31 32 us = SIZ(u); 33 34 /* even roots of negatives provoke an exception */ 35 if (us < 0 && (nth & 1) == 0) 36 SQRT_OF_NEGATIVE; 37 38 /* root extraction interpreted as c^(1/nth) means a zeroth root should 39 provoke a divide by zero, do this even if c==0 */ 40 if (nth == 0) 41 DIVIDE_BY_ZERO; 42 43 if (us == 0) 44 { 45 if (root != NULL) 46 SIZ(root) = 0; 47 SIZ(rem) = 0; 48 return; 49 } 50 51 un = ABS (us); 52 rootn = (un - 1) / nth + 1; 53 54 TMP_MARK; 55 56 /* FIXME: Perhaps disallow root == NULL */ 57 if (root != NULL && u != root) 58 rootp = MPZ_REALLOC (root, rootn); 59 else 60 rootp = TMP_ALLOC_LIMBS (rootn); 61 62 if (u != rem) 63 remp = MPZ_REALLOC (rem, un); 64 else 65 remp = TMP_ALLOC_LIMBS (un); 66 67 up = PTR(u); 68 69 if (nth == 1) 70 { 71 MPN_COPY (rootp, up, un); 72 remn = 0; 73 } 74 else 75 { 76 remn = mpn_rootrem (rootp, remp, up, un, (mp_limb_t) nth); 77 } 78 79 if (root != NULL) 80 { 81 SIZ(root) = us >= 0 ? rootn : -rootn; 82 if (u == root) 83 MPN_COPY (up, rootp, rootn); 84 else if (u == rem) 85 MPN_COPY (up, remp, remn); 86 } 87 88 SIZ(rem) = remn; 89 TMP_FREE; 90 } 91