1 /* mpq_div -- divide two rational numbers.
3 Copyright (C) 1991 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 the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 The GNU MP Library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with the GNU MP Library; see the file COPYING. If not, write to
19 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
26 mpq_div (MP_RAT *quot, const MP_RAT *dividend, const MP_RAT *divisor)
28 mpq_div (quot, dividend, divisor)
30 const MP_RAT *dividend;
31 const MP_RAT *divisor;
44 /* QUOT might be identical to either operand, so don't store the
45 result there until we are finished with the input operands. We
46 dare to overwrite the numerator of QUOT when we are finished
47 with the numerators of DIVIDEND and DIVISOR. */
49 mpz_gcd (&gcd1, &(dividend->num), &(divisor->num));
50 mpz_gcd (&gcd2, &(divisor->den), &(dividend->den));
52 if (gcd1.size > 1 || gcd1.d[0] != 1)
53 mpz_div (&tmp1, &(dividend->num), &gcd1);
55 mpz_set (&tmp1, &(dividend->num));
57 if (gcd2.size > 1 || gcd2.d[0] != 1)
58 mpz_div (&tmp2, &(divisor->den), &gcd2);
60 mpz_set (&tmp2, &(divisor->den));
62 mpz_mul (&numtmp, &tmp1, &tmp2);
64 if (gcd1.size > 1 || gcd1.d[0] != 1)
65 mpz_div (&tmp1, &(divisor->num), &gcd1);
67 mpz_set (&tmp1, &(divisor->num));
69 if (gcd2.size > 1 || gcd2.d[0] != 1)
70 mpz_div (&tmp2, &(dividend->den), &gcd2);
72 mpz_set (&tmp2, &(dividend->den));
74 mpz_mul (&(quot->den), &tmp1, &tmp2);
76 /* We needed to go via NUMTMP to take care of QUOT being the same
77 as either input operands. Now move NUMTMP to QUOT->NUM. */
78 mpz_set (&(quot->num), &numtmp);
80 /* Keep the denominator positive. */
81 if (quot->den.size < 0)
83 quot->den.size = -quot->den.size;
84 quot->num.size = -quot->num.size;