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

Algorithm

Development Platform:

Unix_Linux

  1. /* mpq_inv(dest,src) -- invert a rational number, i.e. set DEST to SRC
  2.    with the numerator and denominator swapped.
  3. Copyright 1991, 1994, 1995, 2000, 2001 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 "gmp.h"
  16. #include "gmp-impl.h"
  17. void
  18. mpq_inv (MP_RAT *dest, const MP_RAT *src)
  19. {
  20.   mp_size_t num_size = src->_mp_num._mp_size;
  21.   mp_size_t den_size = src->_mp_den._mp_size;
  22.   if (num_size == 0)
  23.     DIVIDE_BY_ZERO;
  24.   if (num_size < 0)
  25.     {
  26.       num_size = -num_size;
  27.       den_size = -den_size;
  28.     }
  29.   dest->_mp_den._mp_size = num_size;
  30.   dest->_mp_num._mp_size = den_size;
  31.   /* If dest == src we may just swap the numerator and denominator, but
  32.      we have to ensure the new denominator is positive.  */
  33.   if (dest == src)
  34.     {
  35.       mp_size_t alloc = dest->_mp_num._mp_alloc;
  36.       mp_ptr limb_ptr = dest->_mp_num._mp_d;
  37.       dest->_mp_num._mp_alloc = dest->_mp_den._mp_alloc;
  38.       dest->_mp_num._mp_d = dest->_mp_den._mp_d;
  39.       dest->_mp_den._mp_alloc = alloc;
  40.       dest->_mp_den._mp_d = limb_ptr;
  41.     }
  42.   else
  43.     {
  44.       den_size = ABS (den_size);
  45.       if (dest->_mp_num._mp_alloc < den_size)
  46. _mpz_realloc (&(dest->_mp_num), den_size);
  47.       if (dest->_mp_den._mp_alloc < num_size)
  48. _mpz_realloc (&(dest->_mp_den), num_size);
  49.       MPN_COPY (dest->_mp_num._mp_d, src->_mp_den._mp_d, den_size);
  50.       MPN_COPY (dest->_mp_den._mp_d, src->_mp_num._mp_d, num_size);
  51.     }
  52. }