1/* mpq_canonicalize(op) -- Remove common factors of the denominator and
2   numerator in OP.
3
4Copyright 1991, 1994, 1995, 1996, 2000, 2001, 2005 Free Software Foundation,
5Inc.
6
7This file is part of the GNU MP Library.
8
9The GNU MP Library is free software; you can redistribute it and/or modify
10it under the terms of the GNU Lesser General Public License as published by
11the Free Software Foundation; either version 3 of the License, or (at your
12option) any later version.
13
14The GNU MP Library is distributed in the hope that it will be useful, but
15WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
16or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
17License for more details.
18
19You should have received a copy of the GNU Lesser General Public License
20along with the GNU MP Library.  If not, see http://www.gnu.org/licenses/.  */
21
22#include "gmp.h"
23#include "gmp-impl.h"
24
25void
26mpq_canonicalize (MP_RAT *op)
27{
28  mpz_t gcd;
29  TMP_DECL;
30
31  if (op->_mp_den._mp_size == 0)
32    DIVIDE_BY_ZERO;
33
34  TMP_MARK;
35
36  /* ??? Dunno if the 1+ is needed.  */
37  MPZ_TMP_INIT (gcd, 1 + MAX (ABS (op->_mp_num._mp_size),
38			      ABS (op->_mp_den._mp_size)));
39
40  mpz_gcd (gcd, &(op->_mp_num), &(op->_mp_den));
41  if (! MPZ_EQUAL_1_P (gcd))
42    {
43      mpz_divexact_gcd (&(op->_mp_num), &(op->_mp_num), gcd);
44      mpz_divexact_gcd (&(op->_mp_den), &(op->_mp_den), gcd);
45    }
46
47  if (op->_mp_den._mp_size < 0)
48    {
49      op->_mp_num._mp_size = -op->_mp_num._mp_size;
50      op->_mp_den._mp_size = -op->_mp_den._mp_size;
51    }
52  TMP_FREE;
53}
54