rootrem.c
Upload User: qaz666999
Upload Date: 2022-08-06
Package Size: 2570k
Code Size: 2k
Category:

Algorithm

Development Platform:

Unix_Linux

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