1 /*
2  * This file is part of the Yices SMT Solver.
3  * Copyright (C) 2017 SRI International.
4  *
5  * Yices is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * Yices is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with Yices.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 
20 /*
21  * Operations on rational numbers
22  * - rationals are represented as pairs of 32 bit integers
23  *   or if they are too large as a pointer to a gmp rational.
24  */
25 
26 #include <stdlib.h>
27 #include <stdio.h>
28 #include <stdint.h>
29 #include <stdbool.h>
30 #include <inttypes.h>
31 #include <assert.h>
32 #include <string.h>
33 
34 #include <gmp.h>
35 
36 #include "mt/yices_locks.h"
37 #include "mt/thread_macros.h"
38 #include "terms/rationals.h"
39 #include "terms/mpq_stores.h"
40 #include "utils/gcd.h"
41 
42 
43 
44 static mpq_store_t  mpq_store;
45 
46 
47 /*
48  *  String buffer for parsing.
49  */
50 #ifdef THREAD_SAFE
51 static yices_lock_t string_buffer_lock;
52 #endif
53 static char* string_buffer = NULL;
54 static uint32_t string_buffer_length = 0;
55 
56 /*
57  * Print an error then abort on division by zero
58  */
division_by_zero(void)59 static void division_by_zero(void) {
60   fprintf(stderr, "\nRationals: division by zero\n");
61   abort();
62 }
63 
64 
65 /*
66  * Initialize everything including the string lock
67  * if we're in thread-safe mode.
68  */
init_rationals(void)69 void init_rationals(void){
70   init_mpq_aux();
71   init_mpqstore(&mpq_store);
72 #ifdef THREAD_SAFE
73   create_yices_lock(&string_buffer_lock);
74 #endif
75   string_buffer = NULL;
76   string_buffer_length = 0;
77 }
78 
79 
80 /*
81  * Cleanup: free memory
82  */
cleanup_rationals(void)83 void cleanup_rationals(void){
84   cleanup_mpq_aux();
85   delete_mpqstore(&mpq_store);
86 #ifdef THREAD_SAFE
87   destroy_yices_lock(&string_buffer_lock);
88 #endif
89   safe_free(string_buffer);
90 }
91 
92 
93 /*************************
94  *  MPQ ALLOCATION/FREE  *
95  ************************/
96 
97 /*
98  * Allocates a new mpq object.
99  */
new_mpq(void)100 static inline mpq_ptr new_mpq(void){
101   return mpqstore_alloc(&mpq_store);
102 }
103 
104 
105 /*
106  * Deallocates a new mpq object
107  */
release_mpq(rational_t * r)108 static void release_mpq(rational_t *r){
109   assert(is_ratgmp(r));
110   mpqstore_free(&mpq_store, get_gmp(r));
111 }
112 
113 
114 /*
115  * Free mpq number attached to r if any, then set r to 0/1.
116  * Must be called before r is deleted to prevent memory leaks.
117  */
q_clear(rational_t * r)118 void q_clear(rational_t *r) {
119   if (is_ratgmp(r)) {
120     release_mpq(r);
121   }
122   r->s.num = 0;
123   r->s.den = ONE_DEN;
124 }
125 
126 
127 
128 /*******************
129  *  NORMALIZATION  *
130  ******************/
131 
132 /*
133  * Bounds on numerator and denominators.
134  *
135  * a/b can be safely stored as a pair (int32_t/uint32_t)
136  * if MIN_NUMERATOR <= a <= MAX_NUMERATOR
137  * and 1 <= b <= MAX_DENOMINATOR
138  *
139  * otherwise a/b must be stored as a gmp rational.
140  *
141  * The bounds are such that
142  * - (a/1)+(b/1), (a/1) - (b/1) can be computed using
143  *   32bit arithmetic without overflow.
144  * - a/b stored as a pair implies -a/b and b/a can be stored
145  *   as pairs too.
146  */
147 #define MAX_NUMERATOR (INT32_MAX>>1)
148 #define MIN_NUMERATOR (-MAX_NUMERATOR)
149 #define MAX_DENOMINATOR MAX_NUMERATOR
150 
151 
152 /*
153  * Store num/den in r
154  */
set_rat32(rational_t * r,int32_t num,uint32_t den)155 static inline void set_rat32(rational_t *r, int32_t num, uint32_t den) {
156   assert(MIN_NUMERATOR <= num && num <= MAX_NUMERATOR && den <= MAX_DENOMINATOR);
157   r->s.den = den << 1;
158   r->s.num = num;
159 }
160 
161 
162 /*
163  * Normalization: construct rational a/b when
164  * a and b are two 64bit numbers.
165  * - b must be non-zero
166  */
q_set_int64(rational_t * r,int64_t a,uint64_t b)167 void q_set_int64(rational_t *r, int64_t a, uint64_t b) {
168   uint64_t abs_a;
169   mpq_ptr q;
170   bool a_positive;
171 
172   assert(b > 0);
173 
174   if (a == 0 || (b == 1 && MIN_NUMERATOR <= a && a <= MAX_NUMERATOR)) {
175     if (is_ratgmp(r)) {
176       release_mpq(r);
177     }
178     set_rat32(r, a, 1);
179     return;
180   }
181 
182   // absolute value and sign of a.
183   if (a >= 0) {
184     abs_a = (uint64_t) a;
185     a_positive = true;
186   } else {
187     abs_a = (uint64_t) - a; // Note: this works even when a = -2^63
188     a_positive = false;
189   }
190 
191   // abs_a and b are positive. remove powers of 2
192   while (((abs_a | b) & 15) == 0) {
193     abs_a >>= 4;
194     b >>= 4;
195   }
196   switch ((abs_a | b) & 7) {
197   case 0: abs_a >>= 3; b >>= 3; break;
198   case 1: break;
199   case 2: abs_a >>= 1; b >>= 1; break;
200   case 3: break;
201   case 4: abs_a >>= 2; b >>= 2; break;
202   case 5: break;
203   case 6: abs_a >>= 1; b >>= 1; break;
204   case 7: break;
205   }
206 
207   // abs_a and b are positive, and at least one of them is odd.
208   // if abs_a <= 2 or b <= 2 then gcd = 1.
209   if (abs_a > 2 && b > 2) {
210     uint64_t a_1 = abs_a;
211     uint64_t b_1 = b;
212 
213     // compute gcd of abs_a and b
214     // loop invariant: abs_a is odd or b is odd (or both)
215     for (;;) {
216       if ((a_1 & 1) == 0) {
217         a_1 >>= 1;
218       } else if ((b_1 & 1) == 0) {
219         b_1 >>= 1;
220       } else if (a_1 >= b_1) {
221         a_1 = (a_1 - b_1) >> 1;
222         if (a_1 == 0) break;
223       } else {
224         b_1 = (b_1 - a_1) >> 1;
225       }
226     }
227 
228     // b_1 is gcd(abs_a, b)
229     if (b_1 != 1) {
230       abs_a /= b_1;
231       b /= b_1;
232     }
233   }
234 
235   // abs_a and b are mutually prime and positive
236 
237   // restore a
238   a = a_positive ? ((int64_t) abs_a) : - ((int64_t) abs_a);
239 
240   // assign to r
241   if (abs_a <= MAX_NUMERATOR && b <= MAX_DENOMINATOR) {
242     if (is_ratgmp(r)) {
243       release_mpq(r);
244     }
245     set_rat32(r, (int32_t) a, (uint32_t) b);
246   } else {
247     if (is_ratgmp(r)) {
248       q = get_gmp(r);
249     } else {
250       q = new_mpq();
251       set_ratgmp(r, q);
252     }
253     mpq_set_int64(q, a, b);
254   }
255 }
256 
257 
258 
259 /*
260  * Normalization: construct a/b when a and b are 32 bits
261  */
q_set_int32(rational_t * r,int32_t a,uint32_t b)262 void q_set_int32(rational_t *r, int32_t a, uint32_t b) {
263   uint32_t abs_a;
264   mpq_ptr q;
265   bool a_positive;
266 
267   assert(b > 0);
268 
269   if (a == 0 || (b == 1 && MIN_NUMERATOR <= a && a <= MAX_NUMERATOR)) {
270     if (is_ratgmp(r)) {
271       release_mpq(r);
272     }
273     set_rat32(r, a, 1);
274     return;
275   }
276 
277   // absolute value and sign of a.
278   if (a >= 0) {
279     abs_a = (uint32_t) a;
280     a_positive = true;
281   } else {
282     abs_a = (uint32_t) - a; // Note: this works even when a = -2^31
283     a_positive = false;
284   }
285 
286   // abs_a and b are positive. remove powers of 2
287   while (((abs_a | b) & 15) == 0) {
288     abs_a >>= 4;
289     b >>= 4;
290   }
291   switch ((abs_a | b) & 7) {
292   case 0: abs_a >>= 3; b >>= 3; break;
293   case 1: break;
294   case 2: abs_a >>= 1; b >>= 1; break;
295   case 3: break;
296   case 4: abs_a >>= 2; b >>= 2; break;
297   case 5: break;
298   case 6: abs_a >>= 1; b >>= 1; break;
299   case 7: break;
300   }
301 
302   // abs_a and b are positive, and at least one of them is odd.
303   // if abs_a <= 2 or b <= 2 then gcd = 1.
304   if (abs_a > 2 && b > 2) {
305     uint32_t a_1 = abs_a;
306     uint32_t b_1 = b;
307 
308     // compute gcd of abs_a and b
309     // loop invariant: abs_a is odd or b is odd (or both)
310     for (;;) {
311       if ((a_1 & 1) == 0) {
312         a_1 >>= 1;
313       } else if ((b_1 & 1) == 0) {
314         b_1 >>= 1;
315       } else if (a_1 >= b_1) {
316         a_1 = (a_1 - b_1) >> 1;
317         if (a_1 == 0) break;
318 
319       } else {
320         b_1 = (b_1 - a_1) >> 1;
321       }
322     }
323 
324     // b_1 is gcd(abs_a, b)
325     if (b_1 != 1) {
326       abs_a /= b_1;
327       b /= b_1;
328     }
329   }
330 
331   // abs_a and b are mutually prime and positive
332 
333   // restore a
334   a = a_positive ? ((int32_t) abs_a) : - ((int32_t) abs_a);
335 
336   // assign to r
337   if (abs_a <= MAX_NUMERATOR && b <= MAX_DENOMINATOR) {
338     if (is_ratgmp(r)) {
339       release_mpq(r);
340     }
341     set_rat32(r, (int32_t) a, (uint32_t) b);
342   } else {
343     if (is_ratgmp(r)) {
344       q = get_gmp(r);
345     } else {
346       q = new_mpq();
347       set_ratgmp(r, q);
348     }
349     mpq_set_int32(q, a, b);
350   }
351 }
352 
353 
354 /*
355  * Construct r = a/1
356  */
q_set64(rational_t * r,int64_t a)357 void q_set64(rational_t *r, int64_t a) {
358   mpq_ptr q;
359 
360   if (MIN_NUMERATOR <= a && a <= MAX_NUMERATOR) {
361     if (is_ratgmp(r)){ release_mpq(r); }
362     set_rat32(r, (int32_t) a, 1);
363   } else {
364     if (!is_ratgmp(r)) {
365       q = new_mpq();
366       set_ratgmp(r, q);
367     } else {
368       q = get_gmp(r);
369     }
370     mpq_set_int64(q, a, 1);
371   }
372 }
373 
q_set32(rational_t * r,int32_t a)374 void q_set32(rational_t *r, int32_t a) {
375   mpq_ptr q;
376 
377   if (MIN_NUMERATOR <= a && a <= MAX_NUMERATOR) {
378     if (is_ratgmp(r)) { release_mpq(r); }
379     set_rat32(r, a, 1);
380   } else {
381     if (!is_ratgmp(r)) {
382       q = new_mpq();
383       set_ratgmp(r, q);
384     } else {
385       q = get_gmp(r);
386     }
387     mpq_set_int32(q, a, 1);
388   }
389 }
390 
391 
392 
393 /*
394  * Convert r to a gmp number.
395  * r->num and r->den must have no common factor
396  * and r->den must be non-zero.
397  */
convert_to_gmp(rational_t * r)398 static void convert_to_gmp(rational_t *r) {
399   mpq_ptr q;
400 
401   assert(!is_ratgmp(r));
402 
403   q = new_mpq();
404   mpq_set_int32(q, get_num(r), get_den(r));
405   set_ratgmp(r, q);
406 }
407 
408 
409 /*
410  * Set r to a gmp with value = a.
411  */
set_to_gmp64(rational_t * r,int64_t a)412 static void set_to_gmp64(rational_t *r, int64_t a) {
413   mpq_ptr q;
414 
415   assert(!is_ratgmp(r));
416 
417   q = new_mpq();
418   mpq_set_int64(q, a, 1);
419   set_ratgmp(r, q);
420 }
421 
422 
423 /*****************
424  *  ASSIGNMENTS  *
425  ****************/
426 
427 
428 /*
429  * Convert mpq to a pair of integers if possible.
430  */
q_normalize(rational_t * r)431 void q_normalize(rational_t *r) {
432   mpq_ptr q;
433   unsigned long den;
434   long num;
435 
436   if (is_ratgmp(r)) {
437     q = get_gmp(r);
438     if (mpz_fits_ulong_p(mpq_denref(q)) && mpz_fits_slong_p(mpq_numref(q))) {
439       num = mpz_get_si(mpq_numref(q));
440       den = mpz_get_ui(mpq_denref(q));
441       if (MIN_NUMERATOR <= num && num <= MAX_NUMERATOR && den <= MAX_DENOMINATOR) {
442 	mpqstore_free(&mpq_store, q);
443         set_rat32(r, (int32_t) num, (uint32_t) den);
444       }
445     }
446   }
447 }
448 
449 
450 /*
451  * Prepare to assign an mpq number to r
452  * - if r is not a mpq number, allocate it
453  */
q_prepare(rational_t * r)454 static inline void q_prepare(rational_t *r) {
455   if (!is_ratgmp(r)) {
456     set_ratgmp(r, new_mpq());
457   }
458 }
459 
460 /*
461  * assign r:= z/1
462  */
q_set_mpz(rational_t * r,const mpz_t z)463 void q_set_mpz(rational_t *r, const mpz_t z) {
464   mpq_ptr q;
465 
466   q_prepare(r);
467   q = get_gmp(r);
468   mpq_set_z(q, z);
469   q_normalize(r);
470 }
471 
472 /*
473  * Copy q into r
474  */
q_set_mpq(rational_t * r,const mpq_t q)475 void q_set_mpq(rational_t *r, const mpq_t q) {
476   mpq_ptr qt;
477 
478   q_prepare(r);
479   qt = get_gmp(r);
480   mpq_set(qt, q);
481   q_normalize(r);
482 }
483 
484 /*
485  * Copy r2 into r1
486  */
q_set(rational_t * r1,const rational_t * r2)487 void q_set(rational_t *r1, const rational_t *r2) {
488   mpq_ptr q1, q2;
489 
490   if (is_ratgmp(r2)) {
491     q_prepare(r1);
492     q1 = get_gmp(r1);
493     q2 = get_gmp(r2);
494     mpq_set(q1, q2);
495   } else {
496     if (is_ratgmp(r1)) {
497       release_mpq(r1);
498     }
499     r1->s.num = r2->s.num;
500     r1->s.den = r2->s.den;
501   }
502 }
503 
504 /*
505  * Copy opposite of r2 into r1
506  */
q_set_neg(rational_t * r1,const rational_t * r2)507 void q_set_neg(rational_t *r1, const rational_t *r2) {
508   mpq_ptr q1, q2;
509 
510   if (is_ratgmp(r2)) {
511     q_prepare(r1);
512     q1 = get_gmp(r1);
513     q2 = get_gmp(r2);
514     mpq_neg(q1, q2);
515   } else {
516     if (is_ratgmp(r1)) {
517       release_mpq(r1);
518     }
519     r1->s.num = - r2->s.num;
520     r1->s.den = r2->s.den;
521   }
522 }
523 
524 /*
525  * Copy the absolute value of r2 into r1
526  */
q_set_abs(rational_t * r1,const rational_t * r2)527 void q_set_abs(rational_t *r1, const rational_t *r2) {
528   if (is_ratgmp(r2)) {
529     mpq_ptr q1;
530     mpq_ptr q2;
531     q_prepare(r1);
532     q1 = get_gmp(r1);
533     q2 = get_gmp(r2);
534     mpq_abs(q1, q2);
535   } else {
536     if (is_ratgmp(r1)) {
537       release_mpq(r1);
538     }
539     r1->s.den = r2->s.den;
540     if (r2->s.num < 0) {
541       r1->s.num = - r2->s.num;
542     } else {
543       r1->s.num = r2->s.num;
544     }
545   }
546 }
547 
548 /*
549  * Copy the numerator of r2 into r1
550  * - r1 must be initialized
551  * - r2 and r1 must be different objects
552  */
q_get_num(rational_t * r1,const rational_t * r2)553 void q_get_num(rational_t *r1, const rational_t *r2) {
554   mpq_ptr q1, q2;
555   long num;
556 
557   if (is_ratgmp(r2)) {
558     q2 = get_gmp(r2);
559     if (mpz_fits_slong_p(mpq_numref(q2))) {
560       num = mpz_get_si(mpq_numref(q2));
561       if (MIN_NUMERATOR <= num && num <= MAX_NUMERATOR) {
562         if (is_ratgmp(r1)){ release_mpq(r1); }
563         set_rat32(r1, num, 1);
564         return;
565       }
566     }
567     q_prepare(r1);
568     q1 = get_gmp(r1);
569     mpq_set_z(q1,  mpq_numref(q2));
570   } else {
571     if (is_ratgmp(r1)){ release_mpq(r1); }
572     set_rat32(r1, get_num(r2), 1);
573   }
574 }
575 
576 
577 /*
578  * Copy the denominator of r2 into r1
579  * - r1 must be initialized
580  * - r1 and r2 must be different objects
581  */
q_get_den(rational_t * r1,const rational_t * r2)582 void q_get_den(rational_t *r1, const rational_t *r2) {
583   mpq_ptr q1, q2;
584   unsigned long den;
585 
586   if (is_ratgmp(r2)) {
587     q2 = get_gmp(r2);
588     if (mpz_fits_ulong_p(mpq_denref(q2))) {
589       den = mpz_get_ui(mpq_denref(q2));
590       if (den <= MAX_DENOMINATOR) {
591         if (is_ratgmp(r1)){ release_mpq(r1); }
592         r1->s.num = den;
593         r1->s.den = ONE_DEN;
594         return;
595       }
596     }
597     q_prepare(r1);
598     q1 = get_gmp(r1);
599     mpq_set_z(q1, mpq_denref(q2));
600 
601   } else {
602     if (is_ratgmp(r1)){ release_mpq(r1); }
603     r1->s.num = get_den(r2);
604     r1->s.den = ONE_DEN;
605   }
606 }
607 
608 
609 /*******************************************
610  *  PARSING: CONVERT STRINGS TO RATIONALS  *
611  ******************************************/
612 
613 /*
614  * Resize string_buffer if necessary
615  */
resize_string_buffer(uint32_t new_size)616 static void resize_string_buffer(uint32_t new_size) {
617   uint32_t n;
618 
619   if (string_buffer_length < new_size) {
620     /*
621      * try to make buffer 50% larger
622      * in principle the n += n >> 1 could overflow but
623      * then (n < new_size) will be true
624      * so n will be fixed to new_size.
625      *
626      * all this is very unlikely to happen in practice
627      * (this would require extremely large strings).
628      */
629     n = string_buffer_length + 1;
630     n += n >> 1;
631     if (n < new_size) n = new_size;
632 
633     string_buffer = (char *) safe_realloc(string_buffer, n);
634     string_buffer_length = n;
635   }
636 }
637 
638 
639 /*
640  * Assign q0 to r and try to convert to a pair of integers.
641  * - q0 must be canonicalized
642  * - return 0.
643  */
q_set_q0(rational_t * r,mpq_t * q0)644 static int q_set_q0(rational_t *r, mpq_t *q0) {
645   mpq_ptr q;
646   unsigned long den;
647   long num;
648 
649   // try to store q0 as a pair num/den
650   if (mpz_fits_ulong_p(mpq_denref(*q0)) && mpz_fits_slong_p(mpq_numref(*q0))) {
651     num = mpz_get_si(mpq_numref(*q0));
652     den = mpz_get_ui(mpq_denref(*q0));
653     if (MIN_NUMERATOR <= num && num <= MAX_NUMERATOR && den <= MAX_DENOMINATOR) {
654       if (is_ratgmp(r)){ release_mpq(r); }
655       set_rat32(r, (int32_t) num, (uint32_t) den);
656       return 0;
657     }
658   }
659 
660   // copy q0
661   if (!is_ratgmp(r)) {
662     q_prepare(r);
663   }
664   q = get_gmp(r);
665   mpq_set(q, *q0);
666   return 0;
667 }
668 
669 /*
670  * Conversion from a string in format supported by gmp:
671  *   <+/->numerator/denominator or <+/->numerator
672  * with numerator and denominator in base 10.
673  * - returns -1 and leaves r unchanged if s is not in that format
674  * - returns -2 and leaves r unchanged if the denominator is zero
675  * - returns 0 otherwise
676  */
q_set_from_string(rational_t * r,const char * s)677 int q_set_from_string(rational_t *r, const char *s) {
678   int retval;
679   mpq_t q0;
680 
681   mpq_init2(q0, 64);
682   // GMP rejects an initial '+' so skip it
683   if (*s == '+') s ++;
684   if (mpq_set_str(q0, s, 10) < 0){
685     retval = -1;
686     goto clean_up;
687   }
688   if (mpz_sgn(mpq_denref(q0)) == 0){
689     retval = -2; // the denominator is zero
690     goto clean_up;
691   }
692   mpq_canonicalize(q0);
693   retval = q_set_q0(r, &q0);
694 
695  clean_up:
696   mpq_clear(q0);
697   return retval;
698 }
699 
700 /*
701  * Conversion from a string using the given base.
702  * Base is interpreted as in gmp: either 0 or an integer from 2 to 36.
703  * If base = 0, then the base is determined independently for the
704  * numerator and denominator from the first characters.
705  * Prefixes  0x or 0b or 0 indicate base 16, 2, or 8,
706  * otherwise, the base is 10.
707  */
q_set_from_string_base(rational_t * r,const char * s,int32_t base)708 int q_set_from_string_base(rational_t *r, const char *s, int32_t base) {
709   int retval;
710   mpq_t q0;
711 
712   mpq_init2(q0, 64);
713 
714 
715   // GMP rejects an initial '+' so skip it
716   if (*s == '+') s ++;
717   assert(0 == base || (2 <= base && base <= 36));
718   if (mpq_set_str(q0, s, base) < 0){
719     retval = -1;
720     goto clean_up;
721   }
722   if (mpz_sgn(mpq_denref(q0)) == 0){
723     retval = -2; // the denominator is zero
724     goto clean_up;
725   }
726   mpq_canonicalize(q0);
727   retval = q_set_q0(r, &q0);
728 
729  clean_up:
730 
731   mpq_clear(q0);
732   return retval;
733 
734 }
735 
736 
737 /*
738  * Portable replacement for strtol that we use below to parse an exponent.
739  * The input string must have a non-empty prefix of the form
740  *     <optional sign> <digits>
741  * without space.
742  *
743  * Portability issues with strtol
744  * On some systems strtol("xxx", ..., 10) sets errno to EINVAL
745  * On other systems strtol("xxx", ..., 10) returns 0 and doesn't set errno.
746  */
parse_exponent(const char * s,long * result)747 static bool parse_exponent(const char *s, long *result) {
748   unsigned long x, y;
749   int digit;;
750   char c;
751   bool ok, positive;
752 
753   positive = true;
754   ok = false;
755 
756   c = *s ++;
757   if (c == '-') {
758     positive = false;
759     c = *s ++;
760   } else if (c == '+') {
761     c = *s ++;
762   }
763 
764   x = 0;
765   while ('0' <= c && c <= '9') {
766     ok = true;
767     digit = c - '0';
768     y = 10*x + digit;
769     if (y < x) {
770       // overflow
771       ok = false;
772       break;
773     }
774     x = y;
775     c = *s ++;
776   }
777 
778   if (ok) {
779     if (positive && x <= (unsigned long) LONG_MAX) {
780       *result = (long) x;
781       return true;
782     }
783     if (!positive && x <= (unsigned long) LONG_MIN) {
784       *result = (long) (- x);
785       return true;
786     }
787   }
788 
789   return false;
790 }
791 
792 
793 /*
794  * Conversion from a string in a floating point format
795  * The expected format is one of
796  *   <optional sign> <integer part> . <fractional part>
797  *   <optional sign> <integer part> <exp> <optional sign> <integer>
798  *   <optional sign> <integer part> . <fractional part> <exp> <optional sign> <integer>
799  *
800  * Where <optional sign> is + or - and <exp> is either 'e' or 'E'
801  *
802  * - returns -1 and leaves r unchanged if the string is not in that format
803  * - returns 0 otherwise
804  */
_o_q_set_from_float_string(rational_t * r,const char * s)805 static int _o_q_set_from_float_string(rational_t *r, const char *s) {
806   size_t len;
807   int frac_len, sign;
808   long int exponent;
809   char *b, c;
810   int retval;
811   mpz_t z0;
812   mpq_t q0;
813 
814   mpz_init2(z0, 64);
815   mpq_init2(q0, 64);
816 
817   len = strlen(s);
818   if (len >= (size_t) UINT32_MAX) {
819     // just to be safe if s is really long
820     out_of_memory();
821   }
822   resize_string_buffer(len + 1);
823   c = *s ++;
824 
825   // get sign
826   sign = 1;
827   if (c == '-') {
828     sign = -1;
829     c = * s++;
830   } else if (c == '+') {
831     c = * s ++;
832   }
833 
834   // copy integer part into buffer.
835   b = string_buffer;
836   while ('0' <= c && c <= '9') {
837     *b ++ = c;
838     c = * s ++;
839   }
840 
841   // copy fractional part and count its length
842   frac_len = 0;
843   if (c == '.') {
844     c = *s ++;
845     while ('0' <= c && c <= '9') {
846       frac_len ++;
847       *b ++ = c;
848       c = * s ++;
849     }
850   }
851   *b = '\0'; // end of buffer
852 
853   // check and read exponent
854   exponent = 0;
855   if (c == 'e' || c == 'E') {
856     if (!parse_exponent(s, &exponent)) {
857       retval =  -1;
858       goto clean_up;
859     }
860   }
861 
862 #if 0
863   printf("--> Float conversion\n");
864   printf("--> sign = %d\n", sign);
865   printf("--> mantissa = %s\n", string_buffer);
866   printf("--> frac_len = %d\n", frac_len);
867   printf("--> exponent = %ld\n", exponent);
868 #endif
869 
870   mpq_set_ui(q0, 0, 1);
871 
872   // set numerator
873   if (mpz_set_str(mpq_numref(q0), string_buffer, 10) < 0) {
874     retval =  -1;
875     goto clean_up;
876   }
877   if (sign < 0) {
878     mpq_neg(q0, q0);
879   }
880 
881   // multiply by 10^exponent
882   exponent -= frac_len;
883   if (exponent > 0) {
884     mpz_ui_pow_ui(z0, 10, exponent);
885     mpz_mul(mpq_numref(q0), mpq_numref(q0), z0);
886   } else if (exponent < 0) {
887     // this works even if exponent == LONG_MIN.
888     mpz_ui_pow_ui(mpq_denref(q0), 10UL, (unsigned long) (- exponent));
889     mpq_canonicalize(q0);
890   }
891 
892   retval = q_set_q0(r, &q0);
893 
894  clean_up:
895 
896   mpz_clear(z0);
897   mpq_clear(q0);
898 
899   return retval;
900 
901 }
902 
q_set_from_float_string(rational_t * r,const char * s)903 int q_set_from_float_string(rational_t *r, const char *s) {
904   MT_PROTECT(int, string_buffer_lock, _o_q_set_from_float_string(r, s));
905 }
906 
907 
908 /****************
909  *  ARITHMETIC  *
910  ***************/
911 
912 /*
913  * Add r2 to r1
914  */
q_add(rational_t * r1,const rational_t * r2)915 void q_add(rational_t *r1, const rational_t *r2) {
916   uint64_t den;
917   int64_t num;
918   mpq_ptr q1, q2;
919 
920   if (r1->s.den == ONE_DEN && r2->s.den == ONE_DEN) {
921     assert(is_rat32(r2) && is_rat32(r1));
922     r1->s.num += r2->s.num;
923     if (r1->s.num < MIN_NUMERATOR || r1->s.num > MAX_NUMERATOR) {
924       convert_to_gmp(r1);
925     }
926     return;
927   }
928 
929   if (is_ratgmp(r2)) {
930     if (!is_ratgmp(r1)) convert_to_gmp(r1) ;
931     q1 = get_gmp(r1);
932     q2 = get_gmp(r2);
933     mpq_add(q1, q1, q2);
934   } else if (is_ratgmp(r1)) {
935     q1 = get_gmp(r1);
936     mpq_add_si(q1, get_num(r2), get_den(r2));
937   } else {
938     den = get_den(r1) * ((uint64_t) get_den(r2));
939     num = get_den(r1) * ((int64_t) get_num(r2)) + get_den(r2) * ((int64_t) get_num(r1));
940     q_set_int64(r1, num, den);
941   }
942 }
943 
944 /*
945  * Subtract r2 from r1
946  */
q_sub(rational_t * r1,const rational_t * r2)947 void q_sub(rational_t *r1, const rational_t *r2) {
948   uint64_t den;
949   int64_t num;
950   mpq_ptr q1, q2;
951 
952   if (r1->s.den == ONE_DEN && r2->s.den == ONE_DEN) {
953     assert(is_rat32(r1)  &&  is_rat32(r2));
954     r1->s.num -= r2->s.num;
955     if (r1->s.num < MIN_NUMERATOR || r1->s.num > MAX_NUMERATOR) {
956       convert_to_gmp(r1);
957     }
958     return;
959   }
960 
961   if (is_ratgmp(r2)) {
962     if (!is_ratgmp(r1)) convert_to_gmp(r1);
963     q1 = get_gmp(r1);
964     q2 = get_gmp(r2);
965     mpq_sub(q1, q1, q2);
966   } else if (is_ratgmp(r1)) {
967     q1 = get_gmp(r1);
968     mpq_sub_si(q1, get_num(r2), get_den(r2));
969   } else {
970     den = get_den(r1) * ((uint64_t) get_den(r2));
971     num = get_den(r2) * ((int64_t) get_num(r1)) - get_den(r1) * ((int64_t)get_num(r2));
972     q_set_int64(r1, num, den);
973   }
974 }
975 
976 /*
977  * Negate r
978  */
q_neg(rational_t * r)979 void q_neg(rational_t *r) {
980   if (is_ratgmp(r)){
981     mpq_ptr q = get_gmp(r);
982     mpq_neg(q, q);
983   } else {
984     r->s.num = - r->s.num;
985   }
986 }
987 
988 /*
989  * Invert r
990  */
q_inv(rational_t * r)991 void q_inv(rational_t *r) {
992   uint32_t abs_num;
993 
994   if (is_ratgmp(r)) {
995     mpq_ptr q = get_gmp(r);
996     mpq_inv(q, q);
997   } else if (r->s.num < 0) {
998     abs_num = (uint32_t) - r->s.num;
999     set_rat32(r, - get_den(r), abs_num);
1000   } else if (r->s.num > 0) {
1001     abs_num = (uint32_t) r->s.num;
1002     set_rat32(r, get_den(r), abs_num);
1003   } else {
1004     division_by_zero();
1005   }
1006 }
1007 
1008 /*
1009  * Multiply r1 by r2
1010  */
q_mul(rational_t * r1,const rational_t * r2)1011 void q_mul(rational_t *r1, const rational_t *r2) {
1012   uint64_t den;
1013   int64_t num;
1014   mpq_ptr q1, q2;
1015 
1016   if (r1->s.den == ONE_DEN && r2->s.den == ONE_DEN) {
1017     assert(is_rat32(r1) && is_rat32(r2));
1018     num = r1->s.num * ((int64_t) r2->s.num);
1019     if (MIN_NUMERATOR <= num && num <= MAX_NUMERATOR) {
1020       r1->s.num = (int32_t) num;
1021     } else {
1022       set_to_gmp64(r1, num);
1023     }
1024     return;
1025   }
1026 
1027   if (is_ratgmp(r2)) {
1028     if (is_rat32(r1)) {
1029       convert_to_gmp(r1);
1030     }
1031     q1 = get_gmp(r1);
1032     q2 = get_gmp(r2);
1033     mpq_mul(q1, q1, q2);
1034   } else if (is_ratgmp(r1)){
1035     q1 = get_gmp(r1);
1036     mpq_mul_si(q1, get_num(r2), get_den(r2));
1037   } else {
1038     den = get_den(r1) * ((uint64_t) get_den(r2));
1039     num = get_num(r1) * ((int64_t) get_num(r2));
1040     q_set_int64(r1, num, den);
1041   }
1042 }
1043 
1044 /*
1045  * Divide r1 by r2
1046  */
q_div(rational_t * r1,const rational_t * r2)1047 void q_div(rational_t *r1, const rational_t *r2) {
1048   uint64_t den;
1049   int64_t num;
1050   mpq_ptr q1, q2;
1051 
1052   if (is_ratgmp(r2)) {
1053     if (is_rat32(r1)) convert_to_gmp(r1);
1054     q1 = get_gmp(r1);
1055     q2 = get_gmp(r2);
1056     mpq_div(q1, q1, q2);
1057   } else if (is_ratgmp(r1)){
1058     if (get_num(r2) == 0) {
1059       division_by_zero();
1060     } else {
1061       q1 = get_gmp(r1);
1062       mpq_div_si(q1, get_num(r2), get_den(r2));
1063     }
1064 
1065   } else if (get_num(r2) > 0) {
1066     den = get_den(r1) * ((uint64_t) get_num(r2));
1067     num = get_num(r1) * ((int64_t) get_den(r2));
1068     q_set_int64(r1, num, den);
1069 
1070   } else if (get_num(r2) < 0) {
1071     den = get_den(r1) * ((uint64_t) (- get_num(r2)));
1072     num = get_num(r1) * ( - ((int64_t) get_den(r2)));
1073     q_set_int64(r1, num, den);
1074 
1075   } else {
1076     division_by_zero();
1077   }
1078 }
1079 
1080 /*
1081  * Add r2 * r3 to  r1
1082  */
q_addmul(rational_t * r1,const rational_t * r2,const rational_t * r3)1083 void q_addmul(rational_t *r1, const rational_t *r2, const rational_t *r3) {
1084   int64_t num;
1085   rational_t tmp;
1086 
1087   if (r1->s.den == ONE_DEN && r2->s.den == ONE_DEN && r3->s.den == ONE_DEN) {
1088     assert(is_rat32(r1) && is_rat32(r2) &&  is_rat32(r3));
1089 
1090     num = get_num(r1) + get_num(r2) * ((int64_t) get_num(r3));
1091     if (MIN_NUMERATOR <= num && num <= MAX_NUMERATOR) {
1092       r1->s.num = (int32_t) num;
1093     } else {
1094       set_to_gmp64(r1, num);
1095     }
1096     return;
1097   }
1098 
1099   q_init(&tmp);
1100   q_set(&tmp, r2);
1101   q_mul(&tmp, r3);
1102   q_add(r1, &tmp);
1103   q_clear(&tmp);
1104 }
1105 
1106 
1107 /*
1108  * Subtract r2 * r3 from r1
1109  */
q_submul(rational_t * r1,const rational_t * r2,const rational_t * r3)1110 void q_submul(rational_t *r1, const rational_t *r2, const rational_t *r3) {
1111   int64_t num;
1112   rational_t tmp;
1113 
1114   if (r1->s.den == ONE_DEN && r2->s.den == ONE_DEN && r3->s.den == ONE_DEN) {
1115     assert(is_rat32(r1) && is_rat32(r2) &&  is_rat32(r3));
1116 
1117     num = get_num(r1) - get_num(r2) * ((int64_t) get_num(r3));
1118     if (MIN_NUMERATOR <= num && num <= MAX_NUMERATOR) {
1119       r1->s.num = (int32_t) num;
1120     } else {
1121       set_to_gmp64(r1, num);
1122     }
1123     return;
1124   }
1125 
1126   q_init(&tmp);
1127   q_set(&tmp, r2);
1128   q_mul(&tmp, r3);
1129   q_sub(r1, &tmp);
1130   q_clear(&tmp);
1131 }
1132 
1133 /*
1134  * Increment: add one to r1
1135  */
q_add_one(rational_t * r1)1136 void q_add_one(rational_t *r1) {
1137   mpq_ptr q;
1138 
1139   if (is_ratgmp(r1)) {
1140     q = get_gmp(r1);
1141     mpz_add(mpq_numref(q), mpq_numref(q), mpq_denref(q));
1142   } else {
1143     r1->s.num += get_den(r1);
1144     if (r1->s.num > MAX_NUMERATOR) {
1145       convert_to_gmp(r1);
1146     }
1147   }
1148 }
1149 
1150 /*
1151  * Decrement: subtract one from r1
1152  */
q_sub_one(rational_t * r1)1153 void q_sub_one(rational_t *r1) {
1154   mpq_ptr q;
1155 
1156   if (is_ratgmp(r1)) {
1157     q = get_gmp(r1);
1158     mpz_sub(mpq_numref(q), mpq_numref(q), mpq_denref(q));
1159   } else {
1160     r1->s.num -= get_den(r1);
1161     if (r1->s.num < MIN_NUMERATOR) {
1162       convert_to_gmp(r1);
1163     }
1164   }
1165 }
1166 
1167 
1168 
1169 /***********************
1170  *  CEILING AND FLOOR  *
1171  **********************/
1172 
1173 
1174 // set r to floor(r);
q_floor(rational_t * r)1175 void q_floor(rational_t *r) {
1176   int32_t n;
1177 
1178   if (q_is_integer(r)) return;
1179 
1180   if (is_ratgmp(r)) {
1181     mpq_ptr q = get_gmp(r);
1182     mpz_fdiv_q(mpq_numref(q), mpq_numref(q), mpq_denref(q));
1183     mpz_set_ui(mpq_denref(q), 1UL);
1184   } else {
1185     n = r->s.num / (int32_t) get_den(r);
1186     if (r->s.num < 0) n --;
1187     set_rat32(r, n, 1);
1188   }
1189 }
1190 
1191 // set r to ceil(r)
q_ceil(rational_t * r)1192 void q_ceil(rational_t *r) {
1193   int32_t n;
1194 
1195   if (q_is_integer(r)) return;
1196 
1197   if (is_ratgmp(r)) {
1198     mpq_ptr q = get_gmp(r);
1199     mpz_cdiv_q(mpq_numref(q), mpq_numref(q), mpq_denref(q));
1200     mpz_set_ui(mpq_denref(q), 1UL);
1201   } else {
1202     n = r->s.num / (int32_t) get_den(r);
1203     if (r->s.num > 0) n ++;
1204     set_rat32(r, n, 1);
1205   }
1206 }
1207 
1208 
1209 
1210 /*******************
1211  *  EXPONENTATION  *
1212  ******************/
1213 
1214 /*
1215  * Store r1 * (r2 ^ n) into r1
1216  */
q_mulexp(rational_t * r1,const rational_t * r2,uint32_t n)1217 void q_mulexp(rational_t *r1, const rational_t *r2, uint32_t n) {
1218   rational_t aux;
1219 
1220   if (n <= 3) {
1221     // small exponent:
1222     switch (n) {
1223     case 3: q_mul(r1, r2);
1224     case 2: q_mul(r1, r2);
1225     case 1: q_mul(r1, r2);
1226     case 0: break; // do nothing
1227     }
1228 
1229   } else {
1230     q_init(&aux);
1231     q_set(&aux, r2);
1232 
1233     // compute r1 * aux^n
1234     for (;;) {
1235       assert(n > 0);
1236       if ((n & 1) != 0) {
1237         q_mul(r1, &aux);
1238       }
1239       n >>= 1;
1240       if (n == 0) break;
1241       q_mul(&aux, &aux); // this should work
1242     }
1243 
1244     q_clear(&aux);
1245   }
1246 }
1247 
1248 /*****************
1249  *  LCM and GCD  *
1250  ****************/
1251 
1252 /*
1253  * Get the absolute value of x (converted to uint32_t)
1254  */
abs32(int32_t x)1255 static inline uint32_t abs32(int32_t x) {
1256   return (x >= 0) ? x : -x;
1257 }
1258 
1259 /*
1260  * Store lcm(r1, r2) into r1
1261  * - r1 and r2 must be integer
1262  * - the result is always positive
1263  */
q_lcm(rational_t * r1,const rational_t * r2)1264 void q_lcm(rational_t *r1, const rational_t *r2) {
1265   uint32_t a, b;
1266   uint64_t d;
1267   mpq_ptr q1, q2;
1268 
1269   if (is_rat32(r2)) {
1270     if (is_rat32(r1)) {
1271       // both r1 and r2 are 32bit integers
1272       a = abs32(r1->s.num);
1273       b = abs32(r2->s.num);
1274       d = ((uint64_t) a) * ((uint64_t) (b/gcd32(a, b)));
1275       if (d <= MAX_NUMERATOR) {
1276         set_rat32(r1, d, 1);
1277       } else {
1278         set_to_gmp64(r1, d);
1279       }
1280     } else {
1281       // r2 is 32bits, r1 is gmp
1282       b = abs32(r2->s.num);
1283       q1 = get_gmp(r1);
1284       mpz_lcm_ui(mpq_numref(q1), mpq_numref(q1), b);
1285     }
1286   } else {
1287     // r2 is a gmp rational
1288     if (is_rat32(r1)) convert_to_gmp(r1);
1289     q1 = get_gmp(r1);
1290     q2 = get_gmp(r2);
1291     mpz_lcm(mpq_numref(q1), mpq_numref(q1), mpq_numref(q2));
1292   }
1293 
1294   assert(q_is_pos(r1));
1295 }
1296 
1297 
1298 /*
1299  * Store gcd(r1, r2) into r1
1300  * - r1 and r2 must be integer and non-zero
1301  * - the result is positive
1302  */
q_gcd(rational_t * r1,const rational_t * r2)1303 void q_gcd(rational_t *r1, const rational_t *r2) {
1304   uint32_t a, b, d;
1305   mpq_ptr q1, q2;
1306 
1307   if (is_rat32(r2)) {
1308     if (is_rat32(r1)) {
1309       // r1 and r2 are small integers
1310       a = abs32(r1->s.num);
1311       b = abs32(r2->s.num);
1312       d = gcd32(a, b);
1313     } else {
1314       // r1 is gmp, r2 is a small integer
1315       b = abs32(r2->s.num);
1316       q1 = get_gmp(r1);
1317       d = mpz_gcd_ui(NULL, mpq_numref(q1), b);
1318       release_mpq(r1);
1319     }
1320     assert(d <= MAX_NUMERATOR);
1321     set_rat32(r1, d, 1);
1322   } else {
1323     if (is_rat32(r1)) {
1324       // r1 is a small integer, r2 is a gmp number
1325       a = abs32(r1->s.num);
1326       q2 = get_gmp(r2);
1327       d = mpz_gcd_ui(NULL, mpq_numref(q2), a);
1328       assert(d <= MAX_NUMERATOR);
1329       set_rat32(r1, d, 1);
1330     } else {
1331       // both are gmp numbers
1332       q1 = get_gmp(r1);
1333       q2 = get_gmp(r2);
1334       mpz_gcd(mpq_numref(q1), mpq_numref(q1), mpq_numref(q2));
1335     }
1336   }
1337 }
1338 
1339 
1340 
1341 
1342 
1343 /************************
1344  *  EUCLIDEAN DIVISION  *
1345  ***********************/
1346 
1347 /*
1348  * Quotient/remainder in Euclidean division
1349  * - r1 and r2 must be integer
1350  * - r2 must be positive
1351  */
q_integer_div(rational_t * r1,rational_t * r2)1352 void q_integer_div(rational_t *r1, rational_t *r2) {
1353   int32_t n;
1354   mpq_ptr q1, q2;
1355 
1356   q_normalize(r2);
1357 
1358   if (is_rat32(r2)) {
1359     assert(r2->s.den == ONE_DEN && r2->s.num > 0);
1360     if (is_rat32(r1)) {
1361       // both r1 and r2 are small integers
1362       n = r1->s.num % r2->s.num;  // remainder: n has the same sign as r1 (or n == 0)
1363       r1->s.num /= r2->s.num;     // quotient: same sign as r1, rounded towards 0
1364       if (n < 0) {
1365         r1->s.num --;
1366       }
1367     } else {
1368       // r1 is gmp, r2 is a small integer
1369       q1 = get_gmp(r1);
1370       mpz_fdiv_q_ui(mpq_numref(q1), mpq_numref(q1), r2->s.num);
1371       assert(mpq_is_integer(q1));
1372     }
1373   } else {
1374     q2 = get_gmp(r2);
1375     assert(mpq_is_integer(q2) && mpq_sgn(q2) > 0);
1376     if (is_rat32(r1)) {
1377       /*
1378        * r1 is a small integer, r2 is a gmp rational
1379        * since r2 is normalized and positive, we have r2 > abs(r1)
1380        * so r1 div r2 = 0 if r1 >= 0 or -1 if r1 < 0
1381        */
1382       assert(r1->s.den == ONE_DEN);
1383       if (r1->s.num >= 0) {
1384         r1->s.num = 0;
1385       } else {
1386         r1->s.num = -1;
1387       }
1388     } else {
1389       // both r1 and r2 are gmp rationals
1390       q1 = get_gmp(r1);
1391       mpz_fdiv_q(mpq_numref(q1), mpq_numref(q1), mpq_numref(q2));
1392       assert(mpq_is_integer(q1));
1393     }
1394   }
1395 }
1396 
1397 
1398 /*
1399  * Assign the remainder of r1 divided by r2 to r1
1400  * - both r1 and r2 must be integer
1401  * - r2 must be positive
1402  */
q_integer_rem(rational_t * r1,rational_t * r2)1403 void q_integer_rem(rational_t *r1, rational_t *r2) {
1404   int32_t n;
1405   mpq_ptr q1, q2;
1406 
1407   q_normalize(r2);
1408 
1409   if (is_rat32(r2)){
1410     assert(r2->s.den == ONE_DEN && r2->s.num > 0);
1411     if (is_rat32(r1)) {
1412       /*
1413        * both r1 and r2 are small integers
1414        * Note: the result of (r1->num % r2->num) has the same sign as r1->num
1415        */
1416       n = r1->s.num % r2->s.num;
1417       if (n < 0) {
1418         n += r2->s.num;
1419       }
1420       assert(0 <= n && n < r2->s.num);
1421       r1->s.num = n;
1422     } else {
1423       // r1 is gmp, r2 is a small integer
1424       q1 = get_gmp(r1);
1425       n = mpz_fdiv_ui(mpq_numref(q1), r2->s.num);
1426       assert(0 <= n && n <= MAX_NUMERATOR);
1427       release_mpq(r1);
1428       set_rat32(r1, n, 1);
1429     }
1430   } else {
1431     q2 = get_gmp(r2);
1432 
1433     assert(mpq_is_integer(q2) && mpq_sgn(q2) > 0);
1434     if (is_rat32(r1)) {
1435       /*
1436        * r1 is a small integer, r2 is a gmp rational
1437        * since r2 is normalized and positive, we have r2 > abs(r1)
1438        * so r1 mod r2 = r1 if r1 >= 0
1439        * or r1 mod r2 = (r2 + r1) if r1 < 0
1440        */
1441       assert(r1->s.den == ONE_DEN);
1442       if (r1->s.num < 0) {
1443         mpq_ptr q = new_mpq();
1444         mpq_set_si(q, r1->s.num, 1UL);
1445         mpz_add(mpq_numref(q), mpq_numref(q), mpq_numref(q2));
1446         set_ratgmp(r1, q);
1447         assert(mpq_is_integer(q) && mpq_sgn(q) > 0);
1448       }
1449 
1450     } else {
1451       // both r1 and r2 are gmp rationals
1452       q1 = get_gmp(r1);
1453       mpz_fdiv_r(mpq_numref(q1), mpq_numref(q1), mpq_numref(q2));
1454       assert(mpq_is_integer(q1));
1455     }
1456   }
1457 }
1458 
1459 /*
1460  * Check whether r1 divides r2
1461  *
1462  * Both r1 and r2 must be integers and r1 must be non-zero
1463  */
q_integer_divides(rational_t * r1,const rational_t * r2)1464 bool q_integer_divides(rational_t *r1, const rational_t *r2) {
1465   uint32_t aux;
1466   mpq_ptr q1, q2;
1467 
1468   q_normalize(r1);
1469 
1470   if (is_ratgmp(r1)) {
1471     if (is_ratgmp(r2)) {
1472       q1 = get_gmp(r1);
1473       q2 = get_gmp(r2);
1474       return mpz_divisible_p(mpq_numref(q2), mpq_numref(q1));
1475     } else {
1476       return false;  // abs(r1) > abs(r2) so r1 can't divide r2
1477     }
1478 
1479   } else {
1480     assert(r1->s.den == ONE_DEN);
1481     aux = abs32(r1->s.num);
1482     if (is_ratgmp(r2)) {
1483       q2 = get_gmp(r2);
1484       return mpz_divisible_ui_p(mpq_numref(q2), aux);
1485     } else {
1486       return abs32(r2->s.num) % aux == 0;
1487     }
1488   }
1489 }
1490 
1491 /*
1492  * Check whether r2/r1 is an integer
1493  * - r1 must be non-zero
1494  */
q_divides(const rational_t * r1,const rational_t * r2)1495 bool q_divides(const rational_t *r1, const rational_t *r2) {
1496   rational_t aux;
1497   bool divides;
1498 
1499   if (r1->s.den == ONE_DEN && (r1->s.num == 1 || r1->s.num == -1)) {
1500     assert(is_rat32(r1));
1501     // r1 is +1 or -1
1502     return true;
1503   }
1504 
1505   q_init(&aux);
1506   q_set(&aux, r2);
1507   q_div(&aux, r1);
1508   divides = q_is_integer(&aux);
1509   q_clear(&aux);
1510 
1511   return divides;
1512 }
1513 
1514 
1515 /***********************************
1516  *  SMT2 version of (divides x y)  *
1517  **********************************/
1518 
1519 /*
1520  * (divides r1 r2) is (exist (n::int) r2 = n * r1)
1521  *
1522  * This is the same as q_divides(r1, r2) except that the
1523  * definition allows r1 to be zero. In this case,
1524  *  (divides 0 r2) is (r2 == 0)
1525  */
q_smt2_divides(const rational_t * r1,const rational_t * r2)1526 bool q_smt2_divides(const rational_t *r1, const rational_t *r2) {
1527   if (q_is_zero(r1)) {
1528     return q_is_zero(r2);
1529   } else {
1530     return q_divides(r1, r2);
1531   }
1532 }
1533 
1534 
1535 
1536 
1537 
1538 /**********************
1539  *  GENERALIZED LCM   *
1540  *********************/
1541 
1542 /*
1543  * This computes the LCM of r1 and r2 for arbitrary rationals:
1544  * - if r1 is (a1/b1) and r2 is (a2/b2) then the result is
1545  *    lcm(a1, a2)/gcd(b1, b2).
1546  * - the result is stored in r1
1547  */
q_generalized_lcm(rational_t * r1,rational_t * r2)1548 void q_generalized_lcm(rational_t *r1, rational_t *r2) {
1549   rational_t a1, b1;
1550   rational_t a2, b2;
1551 
1552   if (q_is_integer(r1) && q_is_integer(r2)) {
1553     q_lcm(r1, r2);
1554   } else {
1555     q_init(&a1);
1556     q_get_num(&a1, r1);
1557     q_init(&b1);
1558     q_get_den(&b1, r1);
1559 
1560     q_init(&a2);
1561     q_get_num(&a2, r2);
1562     q_init(&b2);
1563     q_get_den(&b2, r2);
1564 
1565     q_lcm(&a1, &a2); // a1 := lcm(a1, a2)
1566     q_gcd(&b1, &b2); // b1 := gcd(b1, b2)
1567 
1568     // copy the result in r1
1569     q_set(r1, &a1);
1570     q_div(r1, &b1);
1571 
1572     q_clear(&a1);
1573     q_clear(&b1);
1574     q_clear(&a2);
1575     q_clear(&b2);
1576   }
1577 }
1578 
1579 
1580 /*
1581  * This computes the GCD of r1 and r2 for arbitrary non-zero rationals:
1582  * - if r1 is (a1/b1) and r2 is (a2/b2) then the result is
1583  *    gcd(a1, a2)/lcm(b1, b2).
1584  * - the result is stored in r1
1585  */
q_generalized_gcd(rational_t * r1,rational_t * r2)1586 void q_generalized_gcd(rational_t *r1, rational_t *r2) {
1587   rational_t a1, b1;
1588   rational_t a2, b2;
1589 
1590   if (q_is_integer(r1) && q_is_integer(r2)) {
1591     q_lcm(r1, r2);
1592   } else {
1593     q_init(&a1);
1594     q_get_num(&a1, r1);
1595     q_init(&b1);
1596     q_get_den(&b1, r1);
1597 
1598     q_init(&a2);
1599     q_get_num(&a2, r2);
1600     q_init(&b2);
1601     q_get_den(&b2, r2);
1602 
1603     q_gcd(&a1, &a2); // a1 := gcd(a1, a2)
1604     q_lcm(&b1, &b2); // b1 := lcm(b1, b2)
1605 
1606     // copy the result in r1
1607     q_set(r1, &a1);
1608     q_div(r1, &b1);
1609 
1610     q_clear(&a1);
1611     q_clear(&b1);
1612     q_clear(&a2);
1613     q_clear(&b2);
1614   }
1615 }
1616 
1617 /**********************
1618  *  SMT2 DIV AND MOD  *
1619  *********************/
1620 
1621 /*
1622  * SMT-LIB 2.0 definitions for div and mod:
1623  * - if y > 0 then div(x, y) is floor(x/y)
1624  * - if y < 0 then div(x, y) is ceil(x/y)
1625  * - 0 <= mod(x, y) < y
1626  * - x = y * div(x, y) + mod(x, y)
1627  * These operations are defined for any x and non-zero y.
1628  * The terms x and y are not required to be integers.
1629  *
1630  * - q_smt2_div(q, x, y) stores (div x y) in q
1631  * - q_smt2_mod(q, x, y) stores (mod x y) in q
1632  *
1633  * For both functions, y must not be zero.
1634  */
q_smt2_div(rational_t * q,const rational_t * x,const rational_t * y)1635 void q_smt2_div(rational_t *q, const rational_t *x, const rational_t *y) {
1636   assert(q_is_nonzero(y));
1637 
1638   q_set(q, x);
1639   q_div(q, y); // q := x/y
1640   if (q_is_pos(y)) {
1641     q_floor(q);  // round down
1642   } else {
1643     q_ceil(q);  // round up
1644   }
1645 }
1646 
1647 /*
1648  * For debugging: check that 0 <= r < abs(y)
1649  */
1650 #ifndef NDEBUG
plausible_mod(const rational_t * r,const rational_t * y)1651 static bool plausible_mod(const rational_t *r, const rational_t *y) {
1652   rational_t aux;
1653   bool ok;
1654 
1655   assert(q_is_nonzero(y));
1656 
1657   q_init(&aux);
1658   if (q_is_pos(y)) {
1659     q_set(&aux, y);
1660   } else {
1661     q_set_neg(&aux, y);
1662   }
1663   q_normalize(&aux);
1664 
1665   ok = q_is_nonneg(r) && q_lt(r, &aux);
1666 
1667   q_clear(&aux);
1668 
1669   return ok;
1670 }
1671 #endif
1672 
1673 
q_smt2_mod(rational_t * q,const rational_t * x,const rational_t * y)1674 void q_smt2_mod(rational_t *q, const rational_t *x, const rational_t *y) {
1675   assert(q_is_nonzero(y));
1676 
1677   q_smt2_div(q, x, y); // q := (div x y)
1678   q_mul(q, y);         // q := y * (div x y)
1679   q_sub(q, x);         // q := - x + y * (div x y)
1680   q_neg(q);            // q := x - y * (div x y) = (mod x y)
1681 
1682   assert(plausible_mod(q, y));
1683 }
1684 
1685 
1686 /*****************
1687  *  COMPARISONS  *
1688  ****************/
1689 
1690 /*
1691  * Compare r1 and r2
1692  * - returns a negative number if r1 < r2
1693  * - returns 0 if r1 = r2
1694  * - returns a positive number if r1 > r2
1695  */
q_cmp(const rational_t * r1,const rational_t * r2)1696 int q_cmp(const rational_t *r1, const rational_t *r2) {
1697   int64_t num;
1698   mpq_ptr q1, q2;
1699 
1700   if (r1->s.den == ONE_DEN && r2->s.den == ONE_DEN) {
1701     assert(is_rat32(r1) && is_rat32(r2));
1702     return r1->s.num - r2->s.num;
1703   }
1704 
1705   if (is_ratgmp(r1)) {
1706     if (is_ratgmp(r2)) {
1707       q1 = get_gmp(r1);
1708       q2 = get_gmp(r2);
1709       return mpq_cmp(q1, q2);
1710     } else {
1711       q1 = get_gmp(r1);
1712       return mpq_cmp_si(q1, get_num(r2), get_den(r2));
1713     }
1714   } else {
1715     if (is_ratgmp(r2)) {
1716       q2 = get_gmp(r2);
1717       return - mpq_cmp_si(q2, get_num(r1), get_den(r1));
1718     } else {
1719       num = get_den(r2) * ((int64_t) get_num(r1)) - get_den(r1) * ((int64_t) get_num(r2));
1720       return (num < 0 ? -1 : (num > 0));
1721     }
1722   }
1723 }
1724 
1725 /*
1726  * Compare r1 and num/den
1727  */
q_cmp_int32(const rational_t * r1,int32_t num,uint32_t den)1728 int q_cmp_int32(const rational_t *r1, int32_t num, uint32_t den) {
1729   int64_t nn;
1730   mpq_ptr q1;
1731 
1732   if (is_ratgmp(r1)) {
1733     q1 = get_gmp(r1);
1734     return mpq_cmp_si(q1, num, den);
1735   } else {
1736     nn = den * ((int64_t) r1->s.num) - get_den(r1) * ((int64_t) num);
1737     return (nn < 0 ? -1 : (nn > 0));
1738   }
1739 }
1740 
q_cmp_int64(const rational_t * r1,int64_t num,uint64_t den)1741 int q_cmp_int64(const rational_t *r1, int64_t num, uint64_t den) {
1742   int retval;
1743   mpq_ptr q1;
1744   mpq_t q0;
1745 
1746   mpq_init2(q0, 64);
1747   mpq_set_int64(q0, num, den);
1748   mpq_canonicalize(q0);
1749   if (is_ratgmp(r1)){
1750     q1 = get_gmp(r1);
1751     retval = mpq_cmp(q1, q0);
1752   } else {
1753     retval = - mpq_cmp_si(q0, r1->s.num, get_den(r1));
1754   }
1755   mpq_clear(q0);
1756   return retval;
1757 }
1758 
1759 /*
1760  * Check whether r1 and r2 are opposite
1761  */
q_opposite(const rational_t * r1,const rational_t * r2)1762 bool q_opposite(const rational_t *r1, const rational_t *r2) {
1763   rational_t aux;
1764   bool result;
1765 
1766   if (r1->s.den == ONE_DEN && r2->s.den == ONE_DEN) {
1767     assert(is_rat32(r1) && is_rat32(r2));
1768     return r1->s.num + r2->s.num == 0;
1769   }
1770 
1771   q_init(&aux);
1772   q_set(&aux, r1);
1773   q_add(&aux, r2);
1774   result = q_is_zero(&aux);
1775   q_clear(&aux);
1776 
1777   return result;
1778 }
1779 
1780 
1781 /***********************************************
1782  *  CONVERSIONS FROM RATIONALS TO OTHER TYPES  *
1783  **********************************************/
1784 
1785 /*
1786  * Convert r to a 32bit signed integer
1787  * - return false if r is not an integer or does not fit in 32 bits
1788  */
q_get32(rational_t * r,int32_t * v)1789 bool q_get32(rational_t *r, int32_t *v) {
1790   uint32_t d;
1791   mpq_ptr q;
1792 
1793   if (r->s.den == ONE_DEN) {
1794     assert(is_rat32(r));
1795     *v = r->s.num;
1796     return true;
1797   } else if (is_ratgmp(r)){
1798     q = get_gmp(r);
1799     if (mpq_fits_int32(q)) {
1800       mpq_get_int32(q, v, &d);
1801       return d == 1;
1802     }
1803   }
1804   return false;
1805 }
1806 
1807 /*
1808  * Convert r to a 64bit signed integer v
1809  * - return false if r is not an integer or does not fit in 64bits
1810  */
q_get64(rational_t * r,int64_t * v)1811 bool q_get64(rational_t *r, int64_t *v) {
1812   uint64_t d;
1813   mpq_ptr q;
1814 
1815   if (r->s.den == ONE_DEN) {
1816     assert(is_rat32(r));
1817     *v = r->s.num;
1818     return true;
1819   } else if (is_ratgmp(r)){
1820     q = get_gmp(r);
1821     if (mpq_fits_int64(q)) {
1822       mpq_get_int64(q, v, &d);
1823       return d == 1;
1824     }
1825   }
1826   return false;
1827 }
1828 
1829 
1830 /*
1831  * Convert r to a pair of 32 bit integers num/den
1832  * - return false if the numerator or denominator doesn't fit in 32bits
1833  */
q_get_int32(rational_t * r,int32_t * num,uint32_t * den)1834 bool q_get_int32(rational_t *r, int32_t *num, uint32_t *den) {
1835   mpq_ptr q;
1836 
1837   if (is_rat32(r)) {
1838     *num = get_num(r);
1839     *den = get_den(r);
1840     return true;
1841   } else {
1842     q = get_gmp(r);
1843     if (mpq_fits_int32(q)) {
1844       mpq_get_int32(q, num, den);
1845       return true;
1846     }
1847   }
1848   return false;
1849 }
1850 
1851 
1852 /*
1853  * Convert r to a pair of 64bit integers num/den
1854  * - return false if the numerator or denominator doesn't fit in 64bits
1855  */
q_get_int64(rational_t * r,int64_t * num,uint64_t * den)1856 bool q_get_int64(rational_t *r, int64_t *num, uint64_t *den) {
1857   mpq_ptr q;
1858 
1859   if (is_rat32(r)) {
1860     *num = get_num(r);
1861     *den = get_den(r);
1862     return true;
1863   } else {
1864     q = get_gmp(r);
1865     if (mpq_fits_int64(q)) {
1866       mpq_get_int64(q, num, den);
1867       return true;
1868     }
1869   }
1870   return false;
1871 }
1872 
1873 
1874 /*
1875  * Check whether r can be converted to a 32bit integer,
1876  * a 64bit integer, or two a pair num/den of 32bit or 64bit integers.
1877  */
1878 
q_is_int32(rational_t * r)1879 bool q_is_int32(rational_t *r) {
1880   return (is_rat32(r) && r->s.den == ONE_DEN) || (is_ratgmp(r) && mpq_is_int32(get_gmp(r)));
1881 }
1882 
q_is_int64(rational_t * r)1883 bool q_is_int64(rational_t *r) {
1884   return (is_rat32(r) && r->s.den == ONE_DEN) || (is_ratgmp(r) && mpq_is_int64(get_gmp(r)));
1885 }
1886 
q_fits_int32(rational_t * r)1887 bool q_fits_int32(rational_t *r) {
1888   return is_rat32(r) || mpq_fits_int32(get_gmp(r));
1889 }
1890 
q_fits_int64(rational_t * r)1891 bool q_fits_int64(rational_t *r) {
1892   return is_rat32(r) || mpq_fits_int64(get_gmp(r));
1893 }
1894 
1895 
1896 /*
1897  * Size estimate
1898  * - r must be an integer
1899  * - this returns approximately the number of bits to represent r
1900  */
q_size(rational_t * r)1901 uint32_t q_size(rational_t *r) {
1902   size_t n;
1903 
1904   n = 32;
1905   if (is_ratgmp(r)) {
1906     n = mpz_size(mpq_numref(get_gmp(r))) * mp_bits_per_limb;
1907     if (n > (size_t) UINT32_MAX) {
1908       n = UINT32_MAX;
1909     }
1910   }
1911   return (uint32_t) n;
1912 }
1913 
1914 /*
1915  * Convert r to a GMP integer
1916  * - return false if r is not an integer
1917  */
q_get_mpz(rational_t * r,mpz_t z)1918 bool q_get_mpz(rational_t *r, mpz_t z) {
1919   if (r->s.den == ONE_DEN) {
1920     assert(is_rat32(r));
1921     mpz_set_si(z, r->s.num);
1922     return true;
1923   } else if (is_ratgmp(r)){
1924     mpq_ptr q = get_gmp(r);
1925     if (mpq_is_integer(q)) {
1926       mpz_set(z, mpq_numref(q));
1927       return true;
1928     }
1929   }
1930   return false;
1931 }
1932 
1933 /*
1934  * Convert r to a GMP rational
1935  */
q_get_mpq(rational_t * r,mpq_t q)1936 void q_get_mpq(rational_t *r, mpq_t q) {
1937   if (is_ratgmp(r)) {
1938     mpq_set(q, get_gmp(r));
1939   } else {
1940     mpq_set_int32(q, r->s.num, get_den(r));
1941   }
1942 }
1943 
1944 /*
1945  * Convert to a double
1946  */
q_get_double(rational_t * r)1947 double q_get_double(rational_t *r) {
1948   double retval;
1949   mpq_t q0;
1950 
1951   mpq_init2(q0, 64);
1952   q_get_mpq(r, q0);
1953   retval = mpq_get_d(q0);
1954   mpq_clear(q0);
1955 
1956   return retval;
1957 }
1958 
1959 
1960 /**************
1961  *  PRINTING  *
1962  *************/
1963 
1964 /*
1965  * Print r
1966  */
q_print(FILE * f,const rational_t * r)1967 void q_print(FILE *f, const rational_t *r) {
1968   if (is_ratgmp(r)) {
1969     mpq_out_str(f, 10, get_gmp(r));
1970   } else if (r->s.den != ONE_DEN) {
1971     fprintf(f, "%" PRId32 "/%" PRIu32, r->s.num, get_den(r));
1972   } else {
1973     fprintf(f, "%" PRId32, r->s.num);
1974   }
1975 }
1976 
1977 /*
1978  * Print r's absolute value
1979  */
q_print_abs(FILE * f,const rational_t * r)1980 void q_print_abs(FILE *f, const rational_t *r) {
1981   mpq_ptr q;
1982   int32_t abs_num;
1983 
1984   if (is_ratgmp(r)) {
1985     q = get_gmp(r);
1986     if (mpq_sgn(q) < 0) {
1987       mpq_neg(q, q);
1988       mpq_out_str(f, 10, q);
1989       mpq_neg(q, q);
1990     } else {
1991       mpq_out_str(f, 10, q);
1992     }
1993   } else {
1994     abs_num = r->s.num;
1995     if (abs_num < 0) abs_num = - abs_num;
1996 
1997     if (r->s.den != ONE_DEN) {
1998       fprintf(f, "%" PRId32 "/%" PRIu32, abs_num, get_den(r));
1999     } else {
2000       fprintf(f, "%" PRId32, abs_num);
2001     }
2002   }
2003 }
2004 
2005 
2006 /****************
2007  *  HASH CODES  *
2008  ***************/
2009 
2010 /* largest prime less than 2^32 */
2011 #define HASH_MODULUS 4294967291UL
2012 
2013 /*
2014  *  we have  HASH_MODULUS > - MIN_NUMERATOR
2015  *   and HASH_MODULUS > MAX_NUMERATOR
2016  *
2017  * if MIN_NUMERATOR <= r->num <= MAX_NUMERATOR then
2018  * 1) if r->num >= 0 then r_num mod HASH_MODULUS = r_nun
2019  * 2) if r->num < 0 then r_num mod HASH_MODULUS = r_num + HASH_MODULUS
2020  *  so  ((uint32_t) r->num) + HASH_MODULUS = (2^32 + r->num) + HASH_MODULUS
2021  * gives the correct result.
2022  */
q_hash_numerator(const rational_t * r)2023 uint32_t q_hash_numerator(const rational_t *r) {
2024   if (is_ratgmp(r)) {
2025     return (uint32_t) mpz_fdiv_ui(mpq_numref(get_gmp(r)), HASH_MODULUS);
2026   } else if (r->s.num >= 0) {
2027     return (uint32_t) r->s.num;
2028   } else {
2029     return ((uint32_t) r->s.num) + ((uint32_t) HASH_MODULUS);
2030   }
2031 }
2032 
q_hash_denominator(const rational_t * r)2033 uint32_t q_hash_denominator(const rational_t *r) {
2034   if (is_ratgmp(r)) {
2035     return (uint32_t) mpz_fdiv_ui(mpq_denref(get_gmp(r)), HASH_MODULUS);
2036   }
2037   return get_den(r);
2038 }
2039 
q_hash_decompose(const rational_t * r,uint32_t * h_num,uint32_t * h_den)2040 void q_hash_decompose(const rational_t *r, uint32_t *h_num, uint32_t *h_den) {
2041   if (is_ratgmp(r)) {
2042     mpq_ptr q = get_gmp(r);
2043     *h_num = (uint32_t) mpz_fdiv_ui(mpq_numref(q), HASH_MODULUS);
2044     *h_den = (uint32_t) mpz_fdiv_ui(mpq_denref(q), HASH_MODULUS);
2045   } else if (r->s.num >= 0) {
2046     *h_num = (uint32_t) r->s.num;
2047     *h_den = get_den(r);
2048   } else {
2049     *h_num = ((uint32_t) r->s.num) + ((uint32_t) HASH_MODULUS);
2050     *h_den = get_den(r);
2051   }
2052 }
2053 
2054 /***********************
2055  *   RATIONAL ARRAYS   *
2056  **********************/
2057 
2058 /*
2059  * Create and initialize an array of n rationals.
2060  */
new_rational_array(uint32_t n)2061 rational_t *new_rational_array(uint32_t n) {
2062   rational_t *a;
2063   uint32_t i;
2064 
2065   if (n > MAX_RATIONAL_ARRAY_SIZE) {
2066     out_of_memory();
2067   }
2068 
2069   a = (rational_t *) safe_malloc(n * sizeof(rational_t));
2070   for (i=0; i<n; i++) {
2071     q_init(a + i);
2072   }
2073 
2074   return a;
2075 }
2076 
2077 /*
2078  * Delete an array created by the previous function
2079  */
free_rational_array(rational_t * a,uint32_t n)2080 void free_rational_array(rational_t *a, uint32_t n) {
2081   uint32_t i;
2082 
2083   for (i=0; i<n; i++) {
2084     q_clear(a + i);
2085   }
2086   safe_free(a);
2087 }
2088