inv.c revision 1.1.1.1
1/* mpq_inv(dest,src) -- invert a rational number, i.e. set DEST to SRC 2 with the numerator and denominator swapped. 3 4Copyright 1991, 1994, 1995, 2000, 2001 Free Software Foundation, Inc. 5 6This file is part of the GNU MP Library. 7 8The GNU MP Library is free software; you can redistribute it and/or modify 9it under the terms of the GNU Lesser General Public License as published by 10the Free Software Foundation; either version 3 of the License, or (at your 11option) any later version. 12 13The GNU MP Library is distributed in the hope that it will be useful, but 14WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 15or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 16License for more details. 17 18You should have received a copy of the GNU Lesser General Public License 19along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */ 20 21#include "gmp.h" 22#include "gmp-impl.h" 23 24void 25mpq_inv (MP_RAT *dest, const MP_RAT *src) 26{ 27 mp_size_t num_size = src->_mp_num._mp_size; 28 mp_size_t den_size = src->_mp_den._mp_size; 29 30 if (num_size == 0) 31 DIVIDE_BY_ZERO; 32 33 if (num_size < 0) 34 { 35 num_size = -num_size; 36 den_size = -den_size; 37 } 38 dest->_mp_den._mp_size = num_size; 39 dest->_mp_num._mp_size = den_size; 40 41 /* If dest == src we may just swap the numerator and denominator, but 42 we have to ensure the new denominator is positive. */ 43 44 if (dest == src) 45 { 46 mp_size_t alloc = dest->_mp_num._mp_alloc; 47 mp_ptr limb_ptr = dest->_mp_num._mp_d; 48 49 dest->_mp_num._mp_alloc = dest->_mp_den._mp_alloc; 50 dest->_mp_num._mp_d = dest->_mp_den._mp_d; 51 52 dest->_mp_den._mp_alloc = alloc; 53 dest->_mp_den._mp_d = limb_ptr; 54 } 55 else 56 { 57 den_size = ABS (den_size); 58 if (dest->_mp_num._mp_alloc < den_size) 59 _mpz_realloc (&(dest->_mp_num), den_size); 60 61 if (dest->_mp_den._mp_alloc < num_size) 62 _mpz_realloc (&(dest->_mp_den), num_size); 63 64 MPN_COPY (dest->_mp_num._mp_d, src->_mp_den._mp_d, den_size); 65 MPN_COPY (dest->_mp_den._mp_d, src->_mp_num._mp_d, num_size); 66 } 67} 68