0.8.3.33:
[sbcl.git] / src / code / numbers.lisp
1 ;;;; This file contains the definitions of most number functions.
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!KERNEL")
13 \f
14 ;;;; the NUMBER-DISPATCH macro
15
16 (eval-when (:compile-toplevel :load-toplevel :execute)
17
18 ;;; Grovel an individual case to NUMBER-DISPATCH, augmenting RESULT
19 ;;; with the type dispatches and bodies. Result is a tree built of
20 ;;; alists representing the dispatching off each arg (in order). The
21 ;;; leaf is the body to be executed in that case.
22 (defun parse-number-dispatch (vars result types var-types body)
23   (cond ((null vars)
24          (unless (null types) (error "More types than vars."))
25          (when (cdr result)
26            (error "Duplicate case: ~S." body))
27          (setf (cdr result)
28                (sublis var-types body :test #'equal)))
29         ((null types)
30          (error "More vars than types."))
31         (t
32          (flet ((frob (var type)
33                   (parse-number-dispatch
34                    (rest vars)
35                    (or (assoc type (cdr result) :test #'equal)
36                        (car (setf (cdr result)
37                                   (acons type nil (cdr result)))))
38                    (rest types)
39                    (acons `(dispatch-type ,var) type var-types)
40                    body)))
41            (let ((type (first types))
42                  (var (first vars)))
43              (if (and (consp type) (eq (first type) 'foreach))
44                  (dolist (type (rest type))
45                    (frob var type))
46                  (frob var type)))))))
47
48 ;;; our guess for the preferred order in which to do type tests
49 ;;; (cheaper and/or more probable first.)
50 (defparameter *type-test-ordering*
51   '(fixnum single-float double-float integer #!+long-float long-float bignum
52     complex ratio))
53
54 ;;; Should TYPE1 be tested before TYPE2?
55 (defun type-test-order (type1 type2)
56   (let ((o1 (position type1 *type-test-ordering*))
57         (o2 (position type2 *type-test-ordering*)))
58     (cond ((not o1) nil)
59           ((not o2) t)
60           (t
61            (< o1 o2)))))
62
63 ;;; Return an ETYPECASE form that does the type dispatch, ordering the
64 ;;; cases for efficiency.
65 (defun generate-number-dispatch (vars error-tags cases)
66   (if vars
67       (let ((var (first vars))
68             (cases (sort cases #'type-test-order :key #'car)))
69         `((typecase ,var
70             ,@(mapcar (lambda (case)
71                         `(,(first case)
72                           ,@(generate-number-dispatch (rest vars)
73                                                       (rest error-tags)
74                                                       (cdr case))))
75                       cases)
76             (t (go ,(first error-tags))))))
77       cases))
78
79 ) ; EVAL-WHEN
80
81 ;;; This is a vaguely case-like macro that does number cross-product
82 ;;; dispatches. The Vars are the variables we are dispatching off of.
83 ;;; The Type paired with each Var is used in the error message when no
84 ;;; case matches. Each case specifies a Type for each var, and is
85 ;;; executed when that signature holds. A type may be a list
86 ;;; (FOREACH Each-Type*), causing that case to be repeatedly
87 ;;; instantiated for every Each-Type. In the body of each case, any
88 ;;; list of the form (DISPATCH-TYPE Var-Name) is substituted with the
89 ;;; type of that var in that instance of the case.
90 ;;;
91 ;;; As an alternate to a case spec, there may be a form whose CAR is a
92 ;;; symbol. In this case, we apply the CAR of the form to the CDR and
93 ;;; treat the result of the call as a list of cases. This process is
94 ;;; not applied recursively.
95 (defmacro number-dispatch (var-specs &body cases)
96   (let ((res (list nil))
97         (vars (mapcar #'car var-specs))
98         (block (gensym)))
99     (dolist (case cases)
100       (if (symbolp (first case))
101           (let ((cases (apply (symbol-function (first case)) (rest case))))
102             (dolist (case cases)
103               (parse-number-dispatch vars res (first case) nil (rest case))))
104           (parse-number-dispatch vars res (first case) nil (rest case))))
105
106     (collect ((errors)
107               (error-tags))
108       (dolist (spec var-specs)
109         (let ((var (first spec))
110               (type (second spec))
111               (tag (gensym)))
112           (error-tags tag)
113           (errors tag)
114           (errors `(return-from
115                     ,block
116                     (error 'simple-type-error :datum ,var
117                            :expected-type ',type
118                            :format-control
119                            "~@<Argument ~A is not a ~S: ~2I~_~S~:>"
120                            :format-arguments
121                            (list ',var ',type ,var))))))
122
123       `(block ,block
124          (tagbody
125            (return-from ,block
126                         ,@(generate-number-dispatch vars (error-tags)
127                                                     (cdr res)))
128            ,@(errors))))))
129 \f
130 ;;;; binary operation dispatching utilities
131
132 (eval-when (:compile-toplevel :execute)
133
134 ;;; Return NUMBER-DISPATCH forms for rational X float.
135 (defun float-contagion (op x y &optional (rat-types '(fixnum bignum ratio)))
136   `(((single-float single-float) (,op ,x ,y))
137     (((foreach ,@rat-types)
138       (foreach single-float double-float #!+long-float long-float))
139      (,op (coerce ,x '(dispatch-type ,y)) ,y))
140     (((foreach single-float double-float #!+long-float long-float)
141       (foreach ,@rat-types))
142      (,op ,x (coerce ,y '(dispatch-type ,x))))
143     #!+long-float
144     (((foreach single-float double-float long-float) long-float)
145      (,op (coerce ,x 'long-float) ,y))
146     #!+long-float
147     ((long-float (foreach single-float double-float))
148      (,op ,x (coerce ,y 'long-float)))
149     (((foreach single-float double-float) double-float)
150      (,op (coerce ,x 'double-float) ,y))
151     ((double-float single-float)
152      (,op ,x (coerce ,y 'double-float)))))
153
154 ;;; Return NUMBER-DISPATCH forms for bignum X fixnum.
155 (defun bignum-cross-fixnum (fix-op big-op)
156   `(((fixnum fixnum) (,fix-op x y))
157     ((fixnum bignum)
158      (,big-op (make-small-bignum x) y))
159     ((bignum fixnum)
160      (,big-op x (make-small-bignum y)))
161     ((bignum bignum)
162      (,big-op x y))))
163
164 ) ; EVAL-WHEN
165 \f
166 ;;;; canonicalization utilities
167
168 ;;; If IMAGPART is 0, return REALPART, otherwise make a complex. This is
169 ;;; used when we know that REALPART and IMAGPART are the same type, but
170 ;;; rational canonicalization might still need to be done.
171 #!-sb-fluid (declaim (inline canonical-complex))
172 (defun canonical-complex (realpart imagpart)
173   (if (eql imagpart 0)
174       realpart
175       (cond #!+long-float
176             ((and (typep realpart 'long-float)
177                   (typep imagpart 'long-float))
178              (truly-the (complex long-float) (complex realpart imagpart)))
179             ((and (typep realpart 'double-float)
180                   (typep imagpart 'double-float))
181              (truly-the (complex double-float) (complex realpart imagpart)))
182             ((and (typep realpart 'single-float)
183                   (typep imagpart 'single-float))
184              (truly-the (complex single-float) (complex realpart imagpart)))
185             (t
186              (%make-complex realpart imagpart)))))
187
188 ;;; Given a numerator and denominator with the GCD already divided
189 ;;; out, make a canonical rational. We make the denominator positive,
190 ;;; and check whether it is 1.
191 #!-sb-fluid (declaim (inline build-ratio))
192 (defun build-ratio (num den)
193   (multiple-value-bind (num den)
194       (if (minusp den)
195           (values (- num) (- den))
196           (values num den))
197     (cond
198       ((eql den 0)
199        (error 'division-by-zero
200               :operands (list num den)
201               :operation 'build-ratio))
202       ((eql den 1) num)
203       (t (%make-ratio num den)))))
204
205 ;;; Truncate X and Y, but bum the case where Y is 1.
206 #!-sb-fluid (declaim (inline maybe-truncate))
207 (defun maybe-truncate (x y)
208   (if (eql y 1)
209       x
210       (truncate x y)))
211 \f
212 ;;;; COMPLEXes
213
214 (defun upgraded-complex-part-type (spec &optional environment)
215   #!+sb-doc
216   "Return the element type of the most specialized COMPLEX number type that
217    can hold parts of type SPEC."
218   (declare (ignore environment))
219   (cond ((unknown-type-p (specifier-type spec))
220          (error "undefined type: ~S" spec))
221         ((subtypep spec 'single-float)
222          'single-float)
223         ((subtypep spec 'double-float)
224          'double-float)
225         #!+long-float
226         ((subtypep spec 'long-float)
227          'long-float)
228         ((subtypep spec 'rational)
229          'rational)
230         (t
231          'real)))
232
233 (defun complex (realpart &optional (imagpart 0))
234   #!+sb-doc
235   "Return a complex number with the specified real and imaginary components."
236   (flet ((%%make-complex (realpart imagpart)
237            (cond #!+long-float
238                  ((and (typep realpart 'long-float)
239                        (typep imagpart 'long-float))
240                   (truly-the (complex long-float)
241                              (complex realpart imagpart)))
242                  ((and (typep realpart 'double-float)
243                        (typep imagpart 'double-float))
244                   (truly-the (complex double-float)
245                              (complex realpart imagpart)))
246                  ((and (typep realpart 'single-float)
247                        (typep imagpart 'single-float))
248                   (truly-the (complex single-float)
249                              (complex realpart imagpart)))
250                  (t
251                   (%make-complex realpart imagpart)))))
252   (number-dispatch ((realpart real) (imagpart real))
253     ((rational rational)
254      (canonical-complex realpart imagpart))
255     (float-contagion %%make-complex realpart imagpart (rational)))))
256
257 (defun realpart (number)
258   #!+sb-doc
259   "Extract the real part of a number."
260   (typecase number
261     #!+long-float
262     ((complex long-float)
263      (truly-the long-float (realpart number)))
264     ((complex double-float)
265      (truly-the double-float (realpart number)))
266     ((complex single-float)
267      (truly-the single-float (realpart number)))
268     ((complex rational)
269      (sb!kernel:%realpart number))
270     (t
271      number)))
272
273 (defun imagpart (number)
274   #!+sb-doc
275   "Extract the imaginary part of a number."
276   (typecase number
277     #!+long-float
278     ((complex long-float)
279      (truly-the long-float (imagpart number)))
280     ((complex double-float)
281      (truly-the double-float (imagpart number)))
282     ((complex single-float)
283      (truly-the single-float (imagpart number)))
284     ((complex rational)
285      (sb!kernel:%imagpart number))
286     (float
287      (float 0 number))
288     (t
289      0)))
290
291 (defun conjugate (number)
292   #!+sb-doc
293   "Return the complex conjugate of NUMBER. For non-complex numbers, this is
294   an identity."
295   (if (complexp number)
296       (complex (realpart number) (- (imagpart number)))
297       number))
298
299 (defun signum (number)
300   #!+sb-doc
301   "If NUMBER is zero, return NUMBER, else return (/ NUMBER (ABS NUMBER))."
302   (if (zerop number)
303       number
304       (if (rationalp number)
305           (if (plusp number) 1 -1)
306           (/ number (abs number)))))
307 \f
308 ;;;; ratios
309
310 (defun numerator (number)
311   #!+sb-doc
312   "Return the numerator of NUMBER, which must be rational."
313   (numerator number))
314
315 (defun denominator (number)
316   #!+sb-doc
317   "Return the denominator of NUMBER, which must be rational."
318   (denominator number))
319 \f
320 ;;;; arithmetic operations
321
322 (macrolet ((define-arith (op init doc)
323              #!-sb-doc (declare (ignore doc))
324              `(defun ,op (&rest args)
325                 #!+sb-doc ,doc
326                 (if (null args) ,init
327                     (do ((args (cdr args) (cdr args))
328                          (result (car args) (,op result (car args))))
329                         ((null args) result)
330                       ;; to signal TYPE-ERROR when exactly 1 arg of wrong type:
331                       (declare (type number result)))))))
332   (define-arith + 0
333     "Return the sum of its arguments. With no args, returns 0.")
334   (define-arith * 1
335     "Return the product of its arguments. With no args, returns 1."))
336
337 (defun - (number &rest more-numbers)
338   #!+sb-doc
339   "Subtract the second and all subsequent arguments from the first; 
340   or with one argument, negate the first argument."
341   (if more-numbers
342       (do ((nlist more-numbers (cdr nlist))
343            (result number))
344           ((atom nlist) result)
345          (declare (list nlist))
346          (setq result (- result (car nlist))))
347       (- number)))
348
349 (defun / (number &rest more-numbers)
350   #!+sb-doc
351   "Divide the first argument by each of the following arguments, in turn.
352   With one argument, return reciprocal."
353   (if more-numbers
354       (do ((nlist more-numbers (cdr nlist))
355            (result number))
356           ((atom nlist) result)
357          (declare (list nlist))
358          (setq result (/ result (car nlist))))
359       (/ number)))
360
361 (defun 1+ (number)
362   #!+sb-doc
363   "Return NUMBER + 1."
364   (1+ number))
365
366 (defun 1- (number)
367   #!+sb-doc
368   "Return NUMBER - 1."
369   (1- number))
370
371 (eval-when (:compile-toplevel)
372
373 (sb!xc:defmacro two-arg-+/- (name op big-op)
374   `(defun ,name (x y)
375      (number-dispatch ((x number) (y number))
376        (bignum-cross-fixnum ,op ,big-op)
377        (float-contagion ,op x y)
378
379        ((complex complex)
380         (canonical-complex (,op (realpart x) (realpart y))
381                            (,op (imagpart x) (imagpart y))))
382        (((foreach bignum fixnum ratio single-float double-float
383                   #!+long-float long-float) complex)
384         (complex (,op x (realpart y)) (,op (imagpart y))))
385        ((complex (or rational float))
386         (complex (,op (realpart x) y) (imagpart x)))
387
388        (((foreach fixnum bignum) ratio)
389         (let* ((dy (denominator y))
390                (n (,op (* x dy) (numerator y))))
391           (%make-ratio n dy)))
392        ((ratio integer)
393         (let* ((dx (denominator x))
394                (n (,op (numerator x) (* y dx))))
395           (%make-ratio n dx)))
396        ((ratio ratio)
397         (let* ((nx (numerator x))
398                (dx (denominator x))
399                (ny (numerator y))
400                (dy (denominator y))
401                (g1 (gcd dx dy)))
402           (if (eql g1 1)
403               (%make-ratio (,op (* nx dy) (* dx ny)) (* dx dy))
404               (let* ((t1 (,op (* nx (truncate dy g1)) (* (truncate dx g1) ny)))
405                      (g2 (gcd t1 g1))
406                      (t2 (truncate dx g1)))
407                 (cond ((eql t1 0) 0)
408                       ((eql g2 1)
409                        (%make-ratio t1 (* t2 dy)))
410                       (T (let* ((nn (truncate t1 g2))
411                                 (t3 (truncate dy g2))
412                                 (nd (if (eql t2 1) t3 (* t2 t3))))
413                            (if (eql nd 1) nn (%make-ratio nn nd))))))))))))
414
415 ) ; EVAL-WHEN
416
417 (two-arg-+/- two-arg-+ + add-bignums)
418 (two-arg-+/- two-arg-- - subtract-bignum)
419
420 (defun two-arg-* (x y)
421   (flet ((integer*ratio (x y)
422            (if (eql x 0) 0
423                (let* ((ny (numerator y))
424                       (dy (denominator y))
425                       (gcd (gcd x dy)))
426                  (if (eql gcd 1)
427                      (%make-ratio (* x ny) dy)
428                      (let ((nn (* (truncate x gcd) ny))
429                            (nd (truncate dy gcd)))
430                        (if (eql nd 1)
431                            nn
432                            (%make-ratio nn nd)))))))
433          (complex*real (x y)
434            (canonical-complex (* (realpart x) y) (* (imagpart x) y))))
435     (number-dispatch ((x number) (y number))
436       (float-contagion * x y)
437
438       ((fixnum fixnum) (multiply-fixnums x y))
439       ((bignum fixnum) (multiply-bignum-and-fixnum x y))
440       ((fixnum bignum) (multiply-bignum-and-fixnum y x))
441       ((bignum bignum) (multiply-bignums x y))
442
443       ((complex complex)
444        (let* ((rx (realpart x))
445               (ix (imagpart x))
446               (ry (realpart y))
447               (iy (imagpart y)))
448          (canonical-complex (- (* rx ry) (* ix iy)) (+ (* rx iy) (* ix ry)))))
449       (((foreach bignum fixnum ratio single-float double-float
450                  #!+long-float long-float)
451         complex)
452        (complex*real y x))
453       ((complex (or rational float))
454        (complex*real x y))
455
456       (((foreach bignum fixnum) ratio) (integer*ratio x y))
457       ((ratio integer) (integer*ratio y x))
458       ((ratio ratio)
459        (let* ((nx (numerator x))
460               (dx (denominator x))
461               (ny (numerator y))
462               (dy (denominator y))
463               (g1 (gcd nx dy))
464               (g2 (gcd dx ny)))
465          (build-ratio (* (maybe-truncate nx g1)
466                          (maybe-truncate ny g2))
467                       (* (maybe-truncate dx g2)
468                          (maybe-truncate dy g1))))))))
469
470 ;;; Divide two integers, producing a canonical rational. If a fixnum,
471 ;;; we see whether they divide evenly before trying the GCD. In the
472 ;;; bignum case, we don't bother, since bignum division is expensive,
473 ;;; and the test is not very likely to succeed.
474 (defun integer-/-integer (x y)
475   (if (and (typep x 'fixnum) (typep y 'fixnum))
476       (multiple-value-bind (quo rem) (truncate x y)
477         (if (zerop rem)
478             quo
479             (let ((gcd (gcd x y)))
480               (declare (fixnum gcd))
481               (if (eql gcd 1)
482                   (build-ratio x y)
483                   (build-ratio (truncate x gcd) (truncate y gcd))))))
484       (let ((gcd (gcd x y)))
485         (if (eql gcd 1)
486             (build-ratio x y)
487             (build-ratio (truncate x gcd) (truncate y gcd))))))
488
489 (defun two-arg-/ (x y)
490   (number-dispatch ((x number) (y number))
491     (float-contagion / x y (ratio integer))
492
493     ((complex complex)
494      (let* ((rx (realpart x))
495             (ix (imagpart x))
496             (ry (realpart y))
497             (iy (imagpart y)))
498        (if (> (abs ry) (abs iy))
499            (let* ((r (/ iy ry))
500                   (dn (* ry (+ 1 (* r r)))))
501              (canonical-complex (/ (+ rx (* ix r)) dn)
502                                 (/ (- ix (* rx r)) dn)))
503            (let* ((r (/ ry iy))
504                   (dn (* iy (+ 1 (* r r)))))
505              (canonical-complex (/ (+ (* rx r) ix) dn)
506                                 (/ (- (* ix r) rx) dn))))))
507     (((foreach integer ratio single-float double-float) complex)
508      (let* ((ry (realpart y))
509             (iy (imagpart y)))
510        (if (> (abs ry) (abs iy))
511            (let* ((r (/ iy ry))
512                   (dn (* ry (+ 1 (* r r)))))
513              (canonical-complex (/ x dn)
514                                 (/ (- (* x r)) dn)))
515            (let* ((r (/ ry iy))
516                   (dn (* iy (+ 1 (* r r)))))
517              (canonical-complex (/ (* x r) dn)
518                                 (/ (- x) dn))))))
519     ((complex (or rational float))
520      (canonical-complex (/ (realpart x) y)
521                         (/ (imagpart x) y)))
522
523     ((ratio ratio)
524      (let* ((nx (numerator x))
525             (dx (denominator x))
526             (ny (numerator y))
527             (dy (denominator y))
528             (g1 (gcd nx ny))
529             (g2 (gcd dx dy)))
530        (build-ratio (* (maybe-truncate nx g1) (maybe-truncate dy g2))
531                     (* (maybe-truncate dx g2) (maybe-truncate ny g1)))))
532
533     ((integer integer)
534      (integer-/-integer x y))
535
536     ((integer ratio)
537      (if (zerop x)
538          0
539          (let* ((ny (numerator y))
540                 (dy (denominator y))
541                 (gcd (gcd x ny)))
542            (build-ratio (* (maybe-truncate x gcd) dy)
543                         (maybe-truncate ny gcd)))))
544
545     ((ratio integer)
546      (let* ((nx (numerator x))
547             (gcd (gcd nx y)))
548        (build-ratio (maybe-truncate nx gcd)
549                     (* (maybe-truncate y gcd) (denominator x)))))))
550
551 (defun %negate (n)
552   (number-dispatch ((n number))
553     (((foreach fixnum single-float double-float #!+long-float long-float))
554      (%negate n))
555     ((bignum)
556      (negate-bignum n))
557     ((ratio)
558      (%make-ratio (- (numerator n)) (denominator n)))
559     ((complex)
560      (complex (- (realpart n)) (- (imagpart n))))))
561 \f
562 ;;;; TRUNCATE and friends
563
564 (defun truncate (number &optional (divisor 1))
565   #!+sb-doc
566   "Return number (or number/divisor) as an integer, rounded toward 0.
567   The second returned value is the remainder."
568   (macrolet ((truncate-float (rtype)
569                `(let* ((float-div (coerce divisor ',rtype))
570                        (res (%unary-truncate (/ number float-div))))
571                   (values res
572                           (- number
573                              (* (coerce res ',rtype) float-div))))))
574     (number-dispatch ((number real) (divisor real))
575       ((fixnum fixnum) (truncate number divisor))
576       (((foreach fixnum bignum) ratio)
577        (let ((q (truncate (* number (denominator divisor))
578                           (numerator divisor))))
579          (values q (- number (* q divisor)))))
580       ((fixnum bignum)
581        (bignum-truncate (make-small-bignum number) divisor))
582       ((ratio (or float rational))
583        (let ((q (truncate (numerator number)
584                           (* (denominator number) divisor))))
585          (values q (- number (* q divisor)))))
586       ((bignum fixnum)
587        (bignum-truncate number (make-small-bignum divisor)))
588       ((bignum bignum)
589        (bignum-truncate number divisor))
590
591       (((foreach single-float double-float #!+long-float long-float)
592         (or rational single-float))
593        (if (eql divisor 1)
594            (let ((res (%unary-truncate number)))
595              (values res (- number (coerce res '(dispatch-type number)))))
596            (truncate-float (dispatch-type number))))
597       #!+long-float
598       ((long-float (or single-float double-float long-float))
599        (truncate-float long-float))
600       #!+long-float
601       (((foreach double-float single-float) long-float)
602        (truncate-float long-float))
603       ((double-float (or single-float double-float))
604        (truncate-float double-float))
605       ((single-float double-float)
606        (truncate-float double-float))
607       (((foreach fixnum bignum ratio)
608         (foreach single-float double-float #!+long-float long-float))
609        (truncate-float (dispatch-type divisor))))))
610
611 ;;; Declare these guys inline to let them get optimized a little.
612 ;;; ROUND and FROUND are not declared inline since they seem too
613 ;;; obscure and too big to inline-expand by default. Also, this gives
614 ;;; the compiler a chance to pick off the unary float case. Similarly,
615 ;;; CEILING and FLOOR are only maybe-inline for now, so that the
616 ;;; power-of-2 CEILING and FLOOR transforms get a chance.
617 #!-sb-fluid (declaim (inline rem mod fceiling ffloor ftruncate))
618 (declaim (maybe-inline ceiling floor))
619
620 (defun floor (number &optional (divisor 1))
621   #!+sb-doc
622   "Return the greatest integer not greater than number, or number/divisor.
623   The second returned value is (mod number divisor)."
624   ;; If the numbers do not divide exactly and the result of
625   ;; (/ NUMBER DIVISOR) would be negative then decrement the quotient
626   ;; and augment the remainder by the divisor.
627   (multiple-value-bind (tru rem) (truncate number divisor)
628     (if (and (not (zerop rem))
629              (if (minusp divisor)
630                  (plusp number)
631                  (minusp number)))
632         (values (1- tru) (+ rem divisor))
633         (values tru rem))))
634
635 (defun ceiling (number &optional (divisor 1))
636   #!+sb-doc
637   "Return the smallest integer not less than number, or number/divisor.
638   The second returned value is the remainder."
639   ;; If the numbers do not divide exactly and the result of
640   ;; (/ NUMBER DIVISOR) would be positive then increment the quotient
641   ;; and decrement the remainder by the divisor.
642   (multiple-value-bind (tru rem) (truncate number divisor)
643     (if (and (not (zerop rem))
644              (if (minusp divisor)
645                  (minusp number)
646                  (plusp number)))
647         (values (+ tru 1) (- rem divisor))
648         (values tru rem))))
649
650 (defun round (number &optional (divisor 1))
651   #!+sb-doc
652   "Rounds number (or number/divisor) to nearest integer.
653   The second returned value is the remainder."
654   (if (eql divisor 1)
655       (round number)
656       (multiple-value-bind (tru rem) (truncate number divisor)
657         (if (zerop rem)
658             (values tru rem)
659             (let ((thresh (/ (abs divisor) 2)))
660               (cond ((or (> rem thresh)
661                          (and (= rem thresh) (oddp tru)))
662                      (if (minusp divisor)
663                          (values (- tru 1) (+ rem divisor))
664                          (values (+ tru 1) (- rem divisor))))
665                     ((let ((-thresh (- thresh)))
666                        (or (< rem -thresh)
667                            (and (= rem -thresh) (oddp tru))))
668                      (if (minusp divisor)
669                          (values (+ tru 1) (- rem divisor))
670                          (values (- tru 1) (+ rem divisor))))
671                     (t (values tru rem))))))))
672
673 (defun rem (number divisor)
674   #!+sb-doc
675   "Return second result of TRUNCATE."
676   (multiple-value-bind (tru rem) (truncate number divisor)
677     (declare (ignore tru))
678     rem))
679
680 (defun mod (number divisor)
681   #!+sb-doc
682   "Return second result of FLOOR."
683   (let ((rem (rem number divisor)))
684     (if (and (not (zerop rem))
685              (if (minusp divisor)
686                  (plusp number)
687                  (minusp number)))
688         (+ rem divisor)
689         rem)))
690
691 (defmacro !define-float-rounding-function (name op doc)
692   `(defun ,name (number &optional (divisor 1))
693     ,doc
694     (multiple-value-bind (res rem) (,op number divisor)
695       (values (float res (if (floatp rem) rem 1.0)) rem))))
696
697 (!define-float-rounding-function ffloor floor
698   "Same as FLOOR, but returns first value as a float.")
699 (!define-float-rounding-function fceiling ceiling
700   "Same as CEILING, but returns first value as a float." )
701 (!define-float-rounding-function ftruncate truncate
702   "Same as TRUNCATE, but returns first value as a float.")
703 (!define-float-rounding-function fround round
704   "Same as ROUND, but returns first value as a float.")
705 \f
706 ;;;; comparisons
707
708 (defun = (number &rest more-numbers)
709   #!+sb-doc
710   "Return T if all of its arguments are numerically equal, NIL otherwise."
711   (do ((nlist more-numbers (cdr nlist)))
712       ((atom nlist) T)
713      (declare (list nlist))
714      (if (not (= (car nlist) number)) (return nil))))
715
716 (defun /= (number &rest more-numbers)
717   #!+sb-doc
718   "Return T if no two of its arguments are numerically equal, NIL otherwise."
719   (do* ((head number (car nlist))
720         (nlist more-numbers (cdr nlist)))
721        ((atom nlist) t)
722      (declare (list nlist))
723      (unless (do* ((nl nlist (cdr nl)))
724                   ((atom nl) T)
725                (declare (list nl))
726                (if (= head (car nl)) (return nil)))
727        (return nil))))
728
729 (defun < (number &rest more-numbers)
730   #!+sb-doc
731   "Return T if its arguments are in strictly increasing order, NIL otherwise."
732   (do* ((n number (car nlist))
733         (nlist more-numbers (cdr nlist)))
734        ((atom nlist) t)
735      (declare (list nlist))
736      (if (not (< n (car nlist))) (return nil))))
737
738 (defun > (number &rest more-numbers)
739   #!+sb-doc
740   "Return T if its arguments are in strictly decreasing order, NIL otherwise."
741   (do* ((n number (car nlist))
742         (nlist more-numbers (cdr nlist)))
743        ((atom nlist) t)
744      (declare (list nlist))
745      (if (not (> n (car nlist))) (return nil))))
746
747 (defun <= (number &rest more-numbers)
748   #!+sb-doc
749   "Return T if arguments are in strictly non-decreasing order, NIL otherwise."
750   (do* ((n number (car nlist))
751         (nlist more-numbers (cdr nlist)))
752        ((atom nlist) t)
753      (declare (list nlist))
754      (if (not (<= n (car nlist))) (return nil))))
755
756 (defun >= (number &rest more-numbers)
757   #!+sb-doc
758   "Return T if arguments are in strictly non-increasing order, NIL otherwise."
759   (do* ((n number (car nlist))
760         (nlist more-numbers (cdr nlist)))
761        ((atom nlist) t)
762      (declare (list nlist))
763      (if (not (>= n (car nlist))) (return nil))))
764
765 (defun max (number &rest more-numbers)
766   #!+sb-doc
767   "Return the greatest of its arguments."
768   (do ((nlist more-numbers (cdr nlist))
769        (result number))
770       ((null nlist) (return result))
771      (declare (list nlist))
772      (declare (type real number result))
773      (if (> (car nlist) result) (setq result (car nlist)))))
774
775 (defun min (number &rest more-numbers)
776   #!+sb-doc
777   "Return the least of its arguments."
778   (do ((nlist more-numbers (cdr nlist))
779        (result number))
780       ((null nlist) (return result))
781      (declare (list nlist))
782      (declare (type real number result))
783      (if (< (car nlist) result) (setq result (car nlist)))))
784
785 (eval-when (:compile-toplevel :execute)
786
787 ;;; The INFINITE-X-FINITE-Y and INFINITE-Y-FINITE-X args tell us how
788 ;;; to handle the case when X or Y is a floating-point infinity and
789 ;;; the other arg is a rational. (Section 12.1.4.1 of the ANSI spec
790 ;;; says that comparisons are done by converting the float to a
791 ;;; rational when comparing with a rational, but infinities can't be
792 ;;; converted to a rational, so we show some initiative and do it this
793 ;;; way instead.)
794 (defun basic-compare (op &key infinite-x-finite-y infinite-y-finite-x)
795   `(((fixnum fixnum) (,op x y))
796
797     ((single-float single-float) (,op x y))
798     #!+long-float
799     (((foreach single-float double-float long-float) long-float)
800      (,op (coerce x 'long-float) y))
801     #!+long-float
802     ((long-float (foreach single-float double-float))
803      (,op x (coerce y 'long-float)))
804     (((foreach single-float double-float) double-float)
805      (,op (coerce x 'double-float) y))
806     ((double-float single-float)
807      (,op x (coerce y 'double-float)))
808     (((foreach single-float double-float #!+long-float long-float) rational)
809      (if (eql y 0)
810          (,op x (coerce 0 '(dispatch-type x)))
811          (if (float-infinity-p x)
812              ,infinite-x-finite-y
813              (,op (rational x) y))))
814     (((foreach bignum fixnum ratio) float)
815      (if (float-infinity-p y)
816          ,infinite-y-finite-x
817          (,op x (rational y))))))
818 ) ; EVAL-WHEN
819
820 (macrolet ((def-two-arg-</> (name op ratio-arg1 ratio-arg2 &rest cases)
821              `(defun ,name (x y)
822                 (number-dispatch ((x real) (y real))
823                                  (basic-compare
824                                   ,op
825                                   :infinite-x-finite-y
826                                   (,op x (coerce 0 '(dispatch-type x)))
827                                   :infinite-y-finite-x
828                                   (,op (coerce 0 '(dispatch-type y)) y))
829                                  (((foreach fixnum bignum) ratio)
830                                   (,op x (,ratio-arg2 (numerator y)
831                                                       (denominator y))))
832                                  ((ratio integer)
833                                   (,op (,ratio-arg1 (numerator x)
834                                                     (denominator x))
835                                        y))
836                                  ((ratio ratio)
837                                   (,op (* (numerator   (truly-the ratio x))
838                                           (denominator (truly-the ratio y)))
839                                        (* (numerator   (truly-the ratio y))
840                                           (denominator (truly-the ratio x)))))
841                                  ,@cases))))
842   (def-two-arg-</> two-arg-< < floor ceiling
843     ((fixnum bignum)
844      (bignum-plus-p y))
845     ((bignum fixnum)
846      (not (bignum-plus-p x)))
847     ((bignum bignum)
848      (minusp (bignum-compare x y))))
849   (def-two-arg-</> two-arg-> > ceiling floor
850     ((fixnum bignum)
851      (not (bignum-plus-p y)))
852     ((bignum fixnum)
853      (bignum-plus-p x))
854     ((bignum bignum)
855      (plusp (bignum-compare x y)))))
856
857 (defun two-arg-= (x y)
858   (number-dispatch ((x number) (y number))
859     (basic-compare =
860                    ;; An infinite value is never equal to a finite value.
861                    :infinite-x-finite-y nil
862                    :infinite-y-finite-x nil)
863     ((fixnum (or bignum ratio)) nil)
864
865     ((bignum (or fixnum ratio)) nil)
866     ((bignum bignum)
867      (zerop (bignum-compare x y)))
868
869     ((ratio integer) nil)
870     ((ratio ratio)
871      (and (eql (numerator x) (numerator y))
872           (eql (denominator x) (denominator y))))
873
874     ((complex complex)
875      (and (= (realpart x) (realpart y))
876           (= (imagpart x) (imagpart y))))
877     (((foreach fixnum bignum ratio single-float double-float
878                #!+long-float long-float) complex)
879      (and (= x (realpart y))
880           (zerop (imagpart y))))
881     ((complex (or float rational))
882      (and (= (realpart x) y)
883           (zerop (imagpart x))))))
884
885 (defun eql (obj1 obj2)
886   #!+sb-doc
887   "Return T if OBJ1 and OBJ2 represent the same object, otherwise NIL."
888   (or (eq obj1 obj2)
889       (if (or (typep obj2 'fixnum)
890               (not (typep obj2 'number)))
891           nil
892           (macrolet ((foo (&rest stuff)
893                        `(typecase obj2
894                           ,@(mapcar (lambda (foo)
895                                       (let ((type (car foo))
896                                             (fn (cadr foo)))
897                                         `(,type
898                                           (and (typep obj1 ',type)
899                                                (,fn obj1 obj2)))))
900                                     stuff))))
901             (foo
902               (single-float eql)
903               (double-float eql)
904               #!+long-float
905               (long-float eql)
906               (bignum
907                (lambda (x y)
908                  (zerop (bignum-compare x y))))
909               (ratio
910                (lambda (x y)
911                  (and (eql (numerator x) (numerator y))
912                       (eql (denominator x) (denominator y)))))
913               (complex
914                (lambda (x y)
915                  (and (eql (realpart x) (realpart y))
916                       (eql (imagpart x) (imagpart y))))))))))
917 \f
918 ;;;; logicals
919
920 (defun logior (&rest integers)
921   #!+sb-doc
922   "Return the bit-wise or of its arguments. Args must be integers."
923   (declare (list integers))
924   (if integers
925       (do ((result (pop integers) (logior result (pop integers))))
926           ((null integers) result)
927         (declare (integer result)))
928       0))
929
930 (defun logxor (&rest integers)
931   #!+sb-doc
932   "Return the bit-wise exclusive or of its arguments. Args must be integers."
933   (declare (list integers))
934   (if integers
935       (do ((result (pop integers) (logxor result (pop integers))))
936           ((null integers) result)
937         (declare (integer result)))
938       0))
939
940 (defun logand (&rest integers)
941   #!+sb-doc
942   "Return the bit-wise and of its arguments. Args must be integers."
943   (declare (list integers))
944   (if integers
945       (do ((result (pop integers) (logand result (pop integers))))
946           ((null integers) result)
947         (declare (integer result)))
948       -1))
949
950 (defun logeqv (&rest integers)
951   #!+sb-doc
952   "Return the bit-wise equivalence of its arguments. Args must be integers."
953   (declare (list integers))
954   (if integers
955       (do ((result (pop integers) (logeqv result (pop integers))))
956           ((null integers) result)
957         (declare (integer result)))
958       -1))
959
960 (defun lognand (integer1 integer2)
961   #!+sb-doc
962   "Return the complement of the logical AND of integer1 and integer2."
963   (lognand integer1 integer2))
964
965 (defun lognor (integer1 integer2)
966   #!+sb-doc
967   "Return the complement of the logical OR of integer1 and integer2."
968   (lognor integer1 integer2))
969
970 (defun logandc1 (integer1 integer2)
971   #!+sb-doc
972   "Return the logical AND of (LOGNOT integer1) and integer2."
973   (logandc1 integer1 integer2))
974
975 (defun logandc2 (integer1 integer2)
976   #!+sb-doc
977   "Return the logical AND of integer1 and (LOGNOT integer2)."
978   (logandc2 integer1 integer2))
979
980 (defun logorc1 (integer1 integer2)
981   #!+sb-doc
982   "Return the logical OR of (LOGNOT integer1) and integer2."
983   (logorc1 integer1 integer2))
984
985 (defun logorc2 (integer1 integer2)
986   #!+sb-doc
987   "Return the logical OR of integer1 and (LOGNOT integer2)."
988   (logorc2 integer1 integer2))
989
990 (defun lognot (number)
991   #!+sb-doc
992   "Return the bit-wise logical not of integer."
993   (etypecase number
994     (fixnum (lognot (truly-the fixnum number)))
995     (bignum (bignum-logical-not number))))
996
997 (macrolet ((def (name op big-op)
998              `(defun ,name (x y)
999                (number-dispatch ((x integer) (y integer))
1000                  (bignum-cross-fixnum ,op ,big-op)))))
1001   (def two-arg-and logand bignum-logical-and)
1002   (def two-arg-ior logior bignum-logical-ior)
1003   (def two-arg-xor logxor bignum-logical-xor))
1004
1005 (defun logcount (integer)
1006   #!+sb-doc
1007   "Count the number of 1 bits if INTEGER is positive, and the number of 0 bits
1008   if INTEGER is negative."
1009   (etypecase integer
1010     (fixnum
1011      (logcount (truly-the (integer 0 #.(max most-positive-fixnum
1012                                             (lognot most-negative-fixnum)))
1013                           (if (minusp (truly-the fixnum integer))
1014                               (lognot (truly-the fixnum integer))
1015                               integer))))
1016     (bignum
1017      (bignum-logcount integer))))
1018
1019 (defun logtest (integer1 integer2)
1020   #!+sb-doc
1021   "Predicate which returns T if logand of integer1 and integer2 is not zero."
1022   (logtest integer1 integer2))
1023
1024 (defun logbitp (index integer)
1025   #!+sb-doc
1026   "Predicate returns T if bit index of integer is a 1."
1027   (logbitp index integer))
1028
1029 (defun ash (integer count)
1030   #!+sb-doc
1031   "Shifts integer left by count places preserving sign. - count shifts right."
1032   (declare (integer integer count))
1033   (etypecase integer
1034     (fixnum
1035      (cond ((zerop integer)
1036             0)
1037            ((fixnump count)
1038             (let ((length (integer-length (truly-the fixnum integer)))
1039                   (count (truly-the fixnum count)))
1040               (declare (fixnum length count))
1041               (cond ((and (plusp count)
1042                           (> (+ length count)
1043                              (integer-length most-positive-fixnum)))
1044                      (bignum-ashift-left (make-small-bignum integer) count))
1045                     (t
1046                      (truly-the fixnum
1047                                 (ash (truly-the fixnum integer) count))))))
1048            ((minusp count)
1049             (if (minusp integer) -1 0))
1050            (t
1051             (bignum-ashift-left (make-small-bignum integer) count))))
1052     (bignum
1053      (if (plusp count)
1054          (bignum-ashift-left integer count)
1055          (bignum-ashift-right integer (- count))))))
1056
1057 (defun integer-length (integer)
1058   #!+sb-doc
1059   "Return the number of significant bits in the absolute value of integer."
1060   (etypecase integer
1061     (fixnum
1062      (integer-length (truly-the fixnum integer)))
1063     (bignum
1064      (bignum-integer-length integer))))
1065 \f
1066 ;;;; BYTE, bytespecs, and related operations
1067
1068 (defun byte (size position)
1069   #!+sb-doc
1070   "Return a byte specifier which may be used by other byte functions
1071   (e.g. LDB)."
1072   (byte size position))
1073
1074 (defun byte-size (bytespec)
1075   #!+sb-doc
1076   "Return the size part of the byte specifier bytespec."
1077   (byte-size bytespec))
1078
1079 (defun byte-position (bytespec)
1080   #!+sb-doc
1081   "Return the position part of the byte specifier bytespec."
1082   (byte-position bytespec))
1083
1084 (defun ldb (bytespec integer)
1085   #!+sb-doc
1086   "Extract the specified byte from integer, and right justify result."
1087   (ldb bytespec integer))
1088
1089 (defun ldb-test (bytespec integer)
1090   #!+sb-doc
1091   "Return T if any of the specified bits in integer are 1's."
1092   (ldb-test bytespec integer))
1093
1094 (defun mask-field (bytespec integer)
1095   #!+sb-doc
1096   "Extract the specified byte from integer,  but do not right justify result."
1097   (mask-field bytespec integer))
1098
1099 (defun dpb (newbyte bytespec integer)
1100   #!+sb-doc
1101   "Return new integer with newbyte in specified position, newbyte is right justified."
1102   (dpb newbyte bytespec integer))
1103
1104 (defun deposit-field (newbyte bytespec integer)
1105   #!+sb-doc
1106   "Return new integer with newbyte in specified position, newbyte is not right justified."
1107   (deposit-field newbyte bytespec integer))
1108
1109 (defun %ldb (size posn integer)
1110   (logand (ash integer (- posn))
1111           (1- (ash 1 size))))
1112
1113 (defun %mask-field (size posn integer)
1114   (logand integer (ash (1- (ash 1 size)) posn)))
1115
1116 (defun %dpb (newbyte size posn integer)
1117   (let ((mask (1- (ash 1 size))))
1118     (logior (logand integer (lognot (ash mask posn)))
1119             (ash (logand newbyte mask) posn))))
1120
1121 (defun %deposit-field (newbyte size posn integer)
1122   (let ((mask (ash (ldb (byte size 0) -1) posn)))
1123     (logior (logand newbyte mask)
1124             (logand integer (lognot mask)))))
1125 \f
1126 ;;;; BOOLE
1127
1128 ;;; The boole function dispaches to any logic operation depending on
1129 ;;;     the value of a variable. Presently, legal selector values are [0..15].
1130 ;;;     boole is open coded for calls with a constant selector. or with calls
1131 ;;;     using any of the constants declared below.
1132
1133 (defconstant boole-clr 0
1134   #!+sb-doc
1135   "Boole function op, makes BOOLE return 0.")
1136
1137 (defconstant boole-set 1
1138   #!+sb-doc
1139   "Boole function op, makes BOOLE return -1.")
1140
1141 (defconstant boole-1   2
1142   #!+sb-doc
1143   "Boole function op, makes BOOLE return integer1.")
1144
1145 (defconstant boole-2   3
1146   #!+sb-doc
1147   "Boole function op, makes BOOLE return integer2.")
1148
1149 (defconstant boole-c1  4
1150   #!+sb-doc
1151   "Boole function op, makes BOOLE return complement of integer1.")
1152
1153 (defconstant boole-c2  5
1154   #!+sb-doc
1155   "Boole function op, makes BOOLE return complement of integer2.")
1156
1157 (defconstant boole-and 6
1158   #!+sb-doc
1159   "Boole function op, makes BOOLE return logand of integer1 and integer2.")
1160
1161 (defconstant boole-ior 7
1162   #!+sb-doc
1163   "Boole function op, makes BOOLE return logior of integer1 and integer2.")
1164
1165 (defconstant boole-xor 8
1166   #!+sb-doc
1167   "Boole function op, makes BOOLE return logxor of integer1 and integer2.")
1168
1169 (defconstant boole-eqv 9
1170   #!+sb-doc
1171   "Boole function op, makes BOOLE return logeqv of integer1 and integer2.")
1172
1173 (defconstant boole-nand  10
1174   #!+sb-doc
1175   "Boole function op, makes BOOLE return log nand of integer1 and integer2.")
1176
1177 (defconstant boole-nor   11
1178   #!+sb-doc
1179   "Boole function op, makes BOOLE return lognor of integer1 and integer2.")
1180
1181 (defconstant boole-andc1 12
1182   #!+sb-doc
1183   "Boole function op, makes BOOLE return logandc1 of integer1 and integer2.")
1184
1185 (defconstant boole-andc2 13
1186   #!+sb-doc
1187   "Boole function op, makes BOOLE return logandc2 of integer1 and integer2.")
1188
1189 (defconstant boole-orc1  14
1190   #!+sb-doc
1191   "Boole function op, makes BOOLE return logorc1 of integer1 and integer2.")
1192
1193 (defconstant boole-orc2  15
1194   #!+sb-doc
1195   "Boole function op, makes BOOLE return logorc2 of integer1 and integer2.")
1196
1197 (defun boole (op integer1 integer2)
1198   #!+sb-doc
1199   "Bit-wise boolean function on two integers. Function chosen by OP:
1200         0       BOOLE-CLR
1201         1       BOOLE-SET
1202         2       BOOLE-1
1203         3       BOOLE-2
1204         4       BOOLE-C1
1205         5       BOOLE-C2
1206         6       BOOLE-AND
1207         7       BOOLE-IOR
1208         8       BOOLE-XOR
1209         9       BOOLE-EQV
1210         10      BOOLE-NAND
1211         11      BOOLE-NOR
1212         12      BOOLE-ANDC1
1213         13      BOOLE-ANDC2
1214         14      BOOLE-ORC1
1215         15      BOOLE-ORC2"
1216   (case op
1217     (0 (boole 0 integer1 integer2))
1218     (1 (boole 1 integer1 integer2))
1219     (2 (boole 2 integer1 integer2))
1220     (3 (boole 3 integer1 integer2))
1221     (4 (boole 4 integer1 integer2))
1222     (5 (boole 5 integer1 integer2))
1223     (6 (boole 6 integer1 integer2))
1224     (7 (boole 7 integer1 integer2))
1225     (8 (boole 8 integer1 integer2))
1226     (9 (boole 9 integer1 integer2))
1227     (10 (boole 10 integer1 integer2))
1228     (11 (boole 11 integer1 integer2))
1229     (12 (boole 12 integer1 integer2))
1230     (13 (boole 13 integer1 integer2))
1231     (14 (boole 14 integer1 integer2))
1232     (15 (boole 15 integer1 integer2))
1233     (t (error 'type-error :datum op :expected-type '(mod 16)))))
1234 \f
1235 ;;;; GCD and LCM
1236
1237 (defun gcd (&rest numbers)
1238   #!+sb-doc
1239   "Return the greatest common divisor of the arguments, which must be
1240   integers. Gcd with no arguments is defined to be 0."
1241   (cond ((null numbers) 0)
1242         ((null (cdr numbers)) (abs (the integer (car numbers))))
1243         (t
1244          (do ((gcd (the integer (car numbers))
1245                    (gcd gcd (the integer (car rest))))
1246               (rest (cdr numbers) (cdr rest)))
1247              ((null rest) gcd)
1248            (declare (integer gcd)
1249                     (list rest))))))
1250
1251 (defun lcm (&rest numbers)
1252   #!+sb-doc
1253   "Return the least common multiple of one or more integers. LCM of no
1254   arguments is defined to be 1."
1255   (cond ((null numbers) 1)
1256         ((null (cdr numbers)) (abs (the integer (car numbers))))
1257         (t
1258          (do ((lcm (the integer (car numbers))
1259                    (lcm lcm (the integer (car rest))))
1260               (rest (cdr numbers) (cdr rest)))
1261              ((null rest) lcm)
1262            (declare (integer lcm) (list rest))))))
1263
1264 (defun two-arg-lcm (n m)
1265   (declare (integer n m))
1266   (* (truncate (max n m) (gcd n m)) (min n m)))
1267
1268 ;;; Do the GCD of two integer arguments. With fixnum arguments, we use the
1269 ;;; binary GCD algorithm from Knuth's seminumerical algorithms (slightly
1270 ;;; structurified), otherwise we call BIGNUM-GCD. We pick off the special case
1271 ;;; of 0 before the dispatch so that the bignum code doesn't have to worry
1272 ;;; about "small bignum" zeros.
1273 (defun two-arg-gcd (u v)
1274   (cond ((eql u 0) (abs v))
1275         ((eql v 0) (abs u))
1276         (t
1277          (number-dispatch ((u integer) (v integer))
1278            ((fixnum fixnum)
1279             (locally
1280               (declare (optimize (speed 3) (safety 0)))
1281               (do ((k 0 (1+ k))
1282                    (u (abs u) (ash u -1))
1283                    (v (abs v) (ash v -1)))
1284                   ((oddp (logior u v))
1285                    (do ((temp (if (oddp u) (- v) (ash u -1))
1286                               (ash temp -1)))
1287                        (nil)
1288                      (declare (fixnum temp))
1289                      (when (oddp temp)
1290                        (if (plusp temp)
1291                            (setq u temp)
1292                            (setq v (- temp)))
1293                        (setq temp (- u v))
1294                        (when (zerop temp)
1295                          (let ((res (ash u k)))
1296                            (declare (type (signed-byte 31) res)
1297                                     (optimize (inhibit-warnings 3)))
1298                            (return res))))))
1299                 (declare (type (mod 30) k)
1300                          (type (signed-byte 31) u v)))))
1301            ((bignum bignum)
1302             (bignum-gcd u v))
1303            ((bignum fixnum)
1304             (bignum-gcd u (make-small-bignum v)))
1305            ((fixnum bignum)
1306             (bignum-gcd (make-small-bignum u) v))))))
1307 \f
1308 ;;; From discussion on comp.lang.lisp and Akira Kurihara.
1309 (defun isqrt (n)
1310   #!+sb-doc
1311   "Return the root of the nearest integer less than n which is a perfect
1312    square."
1313   (declare (type unsigned-byte n) (values unsigned-byte))
1314   ;; Theoretically (> n 7), i.e., n-len-quarter > 0.
1315   (if (and (fixnump n) (<= n 24))
1316       (cond ((> n 15) 4)
1317             ((> n  8) 3)
1318             ((> n  3) 2)
1319             ((> n  0) 1)
1320             (t 0))
1321       (let* ((n-len-quarter (ash (integer-length n) -2))
1322              (n-half (ash n (- (ash n-len-quarter 1))))
1323              (n-half-isqrt (isqrt n-half))
1324              (init-value (ash (1+ n-half-isqrt) n-len-quarter)))
1325         (loop
1326           (let ((iterated-value
1327                  (ash (+ init-value (truncate n init-value)) -1)))
1328             (unless (< iterated-value init-value)
1329               (return init-value))
1330             (setq init-value iterated-value))))))
1331 \f
1332 ;;;; miscellaneous number predicates
1333
1334 (macrolet ((def (name doc)
1335              `(defun ,name (number) ,doc (,name number))))
1336   (def zerop "Is this number zero?")
1337   (def plusp "Is this real number strictly positive?")
1338   (def minusp "Is this real number strictly negative?")
1339   (def oddp "Is this integer odd?")
1340   (def evenp "Is this integer even?"))
1341 \f
1342 ;;;; modular functions
1343 #.
1344 (collect ((forms))
1345   (flet ((definition (name lambda-list width pattern)
1346            ;; We rely on (SUBTYPEP `(UNSIGNED-BYTE ,WIDTH)
1347            ;;                      'BIGNUM-ELEMENT-TYPE)
1348            `(defun ,name ,lambda-list
1349               (flet ((prepare-argument (x)
1350                        (declare (integer x))
1351                        (etypecase x
1352                          ((unsigned-byte ,width) x)
1353                          (bignum-element-type (logand x ,pattern))
1354                          (fixnum (logand x ,pattern))
1355                          (bignum (logand (%bignum-ref x 0) ,pattern)))))
1356                 (,name ,@(loop for arg in lambda-list
1357                                collect `(prepare-argument ,arg)))))))
1358     (loop for infos being each hash-value of sb!c::*modular-funs*
1359           ;; FIXME: We need to process only "toplevel" functions
1360           unless (eq infos :good)
1361           do (loop for info in infos
1362                    for name = (sb!c::modular-fun-info-name info)
1363                    and width = (sb!c::modular-fun-info-width info)
1364                    and lambda-list = (sb!c::modular-fun-info-lambda-list info)
1365                    for pattern = (1- (ash 1 width))
1366                    do (forms (definition name lambda-list width pattern)))))
1367   `(progn ,@(forms)))