beta-0.89.2
[luatex.git] / source / libs / gmp / gmp-src / mpq / cmp_ui.c
blob93b2265c04ef3b4d04f97052fef1292757639cc0
1 /* mpq_cmp_ui(u,vn,vd) -- Compare U with Vn/Vd. Return positive, zero, or
2 negative based on if U > V, U == V, or U < V. Vn and Vd may have
3 common factors.
5 Copyright 1993, 1994, 1996, 2000-2003, 2005, 2014 Free Software Foundation, Inc.
7 This file is part of the GNU MP Library.
9 The GNU MP Library is free software; you can redistribute it and/or modify
10 it under the terms of either:
12 * the GNU Lesser General Public License as published by the Free
13 Software Foundation; either version 3 of the License, or (at your
14 option) any later version.
18 * the GNU General Public License as published by the Free Software
19 Foundation; either version 2 of the License, or (at your option) any
20 later version.
22 or both in parallel, as here.
24 The GNU MP Library is distributed in the hope that it will be useful, but
25 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
26 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
27 for more details.
29 You should have received copies of the GNU General Public License and the
30 GNU Lesser General Public License along with the GNU MP Library. If not,
31 see https://www.gnu.org/licenses/. */
33 #include "gmp.h"
34 #include "gmp-impl.h"
36 int
37 _mpq_cmp_ui (mpq_srcptr op1, unsigned long int num2, unsigned long int den2)
39 mp_size_t num1_size = SIZ(NUM(op1));
40 mp_size_t den1_size = SIZ(DEN(op1));
41 mp_size_t tmp1_size, tmp2_size;
42 mp_ptr tmp1_ptr, tmp2_ptr;
43 mp_limb_t cy_limb;
44 int cc;
45 TMP_DECL;
47 #if GMP_NAIL_BITS != 0
48 if ((num2 | den2) > GMP_NUMB_MAX)
50 mpq_t op2;
51 mpq_init (op2);
52 mpz_set_ui (mpq_numref (op2), num2);
53 mpz_set_ui (mpq_denref (op2), den2);
54 cc = mpq_cmp (op1, op2);
55 mpq_clear (op2);
56 return cc;
58 #endif
60 /* need canonical sign to get right result */
61 ASSERT (den1_size > 0);
63 if (UNLIKELY (den2 == 0))
64 DIVIDE_BY_ZERO;
66 if (num2 == 0)
67 return num1_size;
68 if (num1_size <= 0)
69 return -1;
71 /* NUM1 x DEN2 is either TMP1_SIZE limbs or TMP1_SIZE-1 limbs.
72 Same for NUM1 x DEN1 with respect to TMP2_SIZE. */
73 if (num1_size > den1_size + 1)
74 /* NUM1 x DEN2 is surely larger in magnitude than NUM2 x DEN1. */
75 return num1_size;
76 if (den1_size > num1_size + 1)
77 /* NUM1 x DEN2 is surely smaller in magnitude than NUM2 x DEN1. */
78 return -num1_size;
80 TMP_MARK;
81 TMP_ALLOC_LIMBS_2 (tmp1_ptr, num1_size + 1, tmp2_ptr, den1_size + 1);
83 cy_limb = mpn_mul_1 (tmp1_ptr, PTR(NUM(op1)), num1_size,
84 (mp_limb_t) den2);
85 tmp1_ptr[num1_size] = cy_limb;
86 tmp1_size = num1_size + (cy_limb != 0);
88 cy_limb = mpn_mul_1 (tmp2_ptr, PTR(DEN(op1)), den1_size,
89 (mp_limb_t) num2);
90 tmp2_ptr[den1_size] = cy_limb;
91 tmp2_size = den1_size + (cy_limb != 0);
93 cc = tmp1_size - tmp2_size != 0
94 ? tmp1_size - tmp2_size : mpn_cmp (tmp1_ptr, tmp2_ptr, tmp1_size);
95 TMP_FREE;
96 return cc;