Upload Tizen:Base source
[external/gmp.git] / tests / mpq / t-cmp_ui.c
1 /* Test mpq_cmp_ui.
2
3 Copyright 1996, 1997, 2001, 2002 Free Software Foundation, Inc.
4
5 This file is part of the GNU MP Library.
6
7 The GNU MP Library is free software; you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or (at your
10 option) any later version.
11
12 The GNU MP Library is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
15 License for more details.
16
17 You should have received a copy of the GNU Lesser General Public License
18 along with the GNU MP Library.  If not, see http://www.gnu.org/licenses/.  */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22
23 #include "gmp.h"
24 #include "gmp-impl.h"
25 #include "tests.h"
26
27 #define NUM(x) (&((x)->_mp_num))
28 #define DEN(x) (&((x)->_mp_den))
29
30 #define SGN(x) ((x) < 0 ? -1 : (x) > 0 ? 1 : 0)
31
32 int
33 ref_mpq_cmp_ui (mpq_t a, unsigned long int bn, unsigned long int bd)
34 {
35   mpz_t ai, bi;
36   int cc;
37
38   mpz_init (ai);
39   mpz_init (bi);
40
41   mpz_mul_ui (ai, NUM (a), bd);
42   mpz_mul_ui (bi, DEN (a), bn);
43   cc = mpz_cmp (ai, bi);
44   mpz_clear (ai);
45   mpz_clear (bi);
46   return cc;
47 }
48
49 #ifndef SIZE
50 #define SIZE 8  /* increasing this lowers the probabilty of finding an error */
51 #endif
52
53 int
54 main (int argc, char **argv)
55 {
56   mpq_t a, b;
57   mp_size_t size;
58   int reps = 10000;
59   int i;
60   int cc, ccref;
61   unsigned long int bn, bd;
62
63   tests_start ();
64
65   if (argc == 2)
66      reps = atoi (argv[1]);
67
68   mpq_init (a);
69   mpq_init (b);
70
71   for (i = 0; i < reps; i++)
72     {
73       size = urandom () % SIZE - SIZE/2;
74       mpz_random2 (NUM (a), size);
75       do
76         {
77           size = urandom () % SIZE - SIZE/2;
78           mpz_random2 (DEN (a), size);
79         }
80       while (mpz_cmp_ui (DEN (a), 0) == 0);
81
82       mpz_random2 (NUM (b), (mp_size_t) 1);
83       mpz_mod_ui (NUM (b), NUM (b), ~(unsigned long int) 0);
84       mpz_add_ui (NUM (b), NUM (b), 1);
85
86       mpz_random2 (DEN (b), (mp_size_t) 1);
87       mpz_mod_ui (DEN (b), DEN (b), ~(unsigned long int) 0);
88       mpz_add_ui (DEN (b), DEN (b), 1);
89
90       mpq_canonicalize (a);
91       mpq_canonicalize (b);
92
93       bn = mpz_get_ui (NUM (b));
94       bd = mpz_get_ui (DEN (b));
95
96       ccref = ref_mpq_cmp_ui (a, bn, bd);
97       cc = mpq_cmp_ui (a, bn, bd);
98
99       if (SGN (ccref) != SGN (cc))
100         abort ();
101     }
102
103   mpq_clear (a);
104   mpq_clear (b);
105
106   tests_end ();
107   exit (0);
108 }