beta-0.89.2
[luatex.git] / source / libs / gmp / gmp-src / mpq / mul.c
blob49d618f3bc1dde032464faebeba008d703990da1
1 /* mpq_mul -- multiply two rational numbers.
3 Copyright 1991, 1994-1996, 2000-2002 Free Software Foundation, Inc.
5 This file is part of the GNU MP Library.
7 The GNU MP Library is free software; you can redistribute it and/or modify
8 it under the terms of either:
10 * the GNU Lesser General Public License as published by the Free
11 Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
16 * the GNU General Public License as published by the Free Software
17 Foundation; either version 2 of the License, or (at your option) any
18 later version.
20 or both in parallel, as here.
22 The GNU MP Library is distributed in the hope that it will be useful, but
23 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
25 for more details.
27 You should have received copies of the GNU General Public License and the
28 GNU Lesser General Public License along with the GNU MP Library. If not,
29 see https://www.gnu.org/licenses/. */
31 #include "gmp.h"
32 #include "gmp-impl.h"
35 void
36 mpq_mul (mpq_ptr prod, mpq_srcptr op1, mpq_srcptr op2)
38 mpz_t gcd1, gcd2;
39 mpz_t tmp1, tmp2;
40 mp_size_t op1_num_size;
41 mp_size_t op1_den_size;
42 mp_size_t op2_num_size;
43 mp_size_t op2_den_size;
44 mp_size_t alloc;
45 TMP_DECL;
47 if (op1 == op2)
49 /* No need for any GCDs when squaring. */
50 mpz_mul (mpq_numref (prod), mpq_numref (op1), mpq_numref (op1));
51 mpz_mul (mpq_denref (prod), mpq_denref (op1), mpq_denref (op1));
52 return;
55 op1_num_size = ABSIZ(NUM(op1));
56 op1_den_size = SIZ(DEN(op1));
57 op2_num_size = ABSIZ(NUM(op2));
58 op2_den_size = SIZ(DEN(op2));
60 if (op1_num_size == 0 || op2_num_size == 0)
62 /* We special case this to simplify allocation logic; gcd(0,x) = x
63 is a singular case for the allocations. */
64 SIZ(NUM(prod)) = 0;
65 PTR(DEN(prod))[0] = 1;
66 SIZ(DEN(prod)) = 1;
67 return;
70 TMP_MARK;
72 alloc = MIN (op1_num_size, op2_den_size);
73 MPZ_TMP_INIT (gcd1, alloc);
75 alloc = MIN (op2_num_size, op1_den_size);
76 MPZ_TMP_INIT (gcd2, alloc);
78 alloc = MAX (op1_num_size, op2_den_size);
79 MPZ_TMP_INIT (tmp1, alloc);
81 alloc = MAX (op2_num_size, op1_den_size);
82 MPZ_TMP_INIT (tmp2, alloc);
84 /* PROD might be identical to either operand, so don't store the result there
85 until we are finished with the input operands. We can overwrite the
86 numerator of PROD when we are finished with the numerators of OP1 and
87 OP2. */
89 mpz_gcd (gcd1, NUM(op1), DEN(op2));
90 mpz_gcd (gcd2, NUM(op2), DEN(op1));
92 mpz_divexact_gcd (tmp1, NUM(op1), gcd1);
93 mpz_divexact_gcd (tmp2, NUM(op2), gcd2);
95 mpz_mul (NUM(prod), tmp1, tmp2);
97 mpz_divexact_gcd (tmp1, DEN(op2), gcd1);
98 mpz_divexact_gcd (tmp2, DEN(op1), gcd2);
100 mpz_mul (DEN(prod), tmp1, tmp2);
102 TMP_FREE;