882f408fb8397f727fa0ab92f7e723df2ca248ad
[platform/upstream/gmp.git] / mpq / canonicalize.c
1 /* mpq_canonicalize(op) -- Remove common factors of the denominator and
2    numerator in OP.
3
4 Copyright 1991, 1994-1996, 2000, 2001, 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 either:
10
11   * the GNU Lesser General Public License as published by the Free
12     Software Foundation; either version 3 of the License, or (at your
13     option) any later version.
14
15 or
16
17   * the GNU General Public License as published by the Free Software
18     Foundation; either version 2 of the License, or (at your option) any
19     later version.
20
21 or both in parallel, as here.
22
23 The GNU MP Library is distributed in the hope that it will be useful, but
24 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
25 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
26 for more details.
27
28 You should have received copies of the GNU General Public License and the
29 GNU Lesser General Public License along with the GNU MP Library.  If not,
30 see https://www.gnu.org/licenses/.  */
31
32 #include "gmp.h"
33 #include "gmp-impl.h"
34
35 void
36 mpq_canonicalize (mpq_t op)
37 {
38   mpz_t gcd;
39   TMP_DECL;
40
41   if (UNLIKELY (SIZ(DEN(op)) == 0))
42     DIVIDE_BY_ZERO;
43
44   TMP_MARK;
45
46   /* ??? Dunno if the 1+ is needed.  */
47   MPZ_TMP_INIT (gcd, 1 + MAX (ABSIZ(NUM(op)),
48                               ABSIZ(DEN(op))));
49
50   mpz_gcd (gcd, NUM(op), DEN(op));
51   if (! MPZ_EQUAL_1_P (gcd))
52     {
53       mpz_divexact_gcd (NUM(op), NUM(op), gcd);
54       mpz_divexact_gcd (DEN(op), DEN(op), gcd);
55     }
56
57   if (SIZ(DEN(op)) < 0)
58     {
59       SIZ(NUM(op)) = -SIZ(NUM(op));
60       SIZ(DEN(op)) = -SIZ(DEN(op));
61     }
62   TMP_FREE;
63 }