[project @ 1998-11-26 09:17:22 by sof]
[ghc-hetmet.git] / ghc / runtime / gmp / mpq_set_si.c
1 /* mpq_set_si(dest,ulong_num,ulong_den) -- Set DEST to the retional number
2    ULONG_NUM/ULONG_DEN.
3
4 Copyright (C) 1991 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 the GNU General Public License as published by
10 the Free Software Foundation; either version 2, or (at your option)
11 any later version.
12
13 The GNU MP Library is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with the GNU MP Library; see the file COPYING.  If not, write to
20 the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
21
22 #include "gmp.h"
23 #include "gmp-impl.h"
24
25 static unsigned long int
26 gcd (x, y)
27      unsigned long int x, y;
28 {
29   for (;;)
30     {
31       x = x % y;
32       if (x == 0)
33         return y;
34       y = y % x;
35       if (y == 0)
36         return x;
37     }
38 }
39
40 void
41 #ifdef __STDC__
42 mpq_set_si (MP_RAT *dest, signed long int num, unsigned long int den)
43 #else
44 mpq_set_si (dest, num, den)
45      MP_RAT *dest;
46      signed long int num;
47      unsigned long int den;
48 #endif
49 {
50   unsigned long int g;
51   unsigned long int abs_num;
52
53   abs_num = ABS (num);
54
55   if (num == 0)
56     {
57       /* Canonicalize 0/d to 0/1.  */
58       den = 1;
59       dest->num.size = 0;
60     }
61   else
62     {
63       /* Remove any common factor in NUM and DEN. */
64       /* Pass DEN as the second argument to gcd, in order to make the
65          gcd function divide by zero if DEN is zero.  */
66       g = gcd (abs_num, den);
67       abs_num /= g;
68       den /= g;
69
70       dest->num.d[0] = abs_num;
71       dest->num.size = num > 0 ? 1 : -1;
72     }
73
74   dest->den.d[0] = den;
75   dest->den.size = 1;
76 }