0.7.6.13:
[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)
215   #!+sb-doc
216   "Return the element type of the most specialized COMPLEX number type that
217    can hold parts of type SPEC."
218   (cond ((unknown-type-p (specifier-type spec))
219          (error "undefined type: ~S" spec))
220         ((subtypep spec 'single-float)
221          'single-float)
222         ((subtypep spec 'double-float)
223          'double-float)
224         #!+long-float
225         ((subtypep spec 'long-float)
226          'long-float)
227         ((subtypep spec 'rational)
228          'rational)
229         (t
230          'real)))
231
232 (defun complex (realpart &optional (imagpart 0))
233   #!+sb-doc
234   "Return a complex number with the specified real and imaginary components."
235   (flet ((%%make-complex (realpart imagpart)
236            (cond #!+long-float
237                  ((and (typep realpart 'long-float)
238                        (typep imagpart 'long-float))
239                   (truly-the (complex long-float)
240                              (complex realpart imagpart)))
241                  ((and (typep realpart 'double-float)
242                        (typep imagpart 'double-float))
243                   (truly-the (complex double-float)
244                              (complex realpart imagpart)))
245                  ((and (typep realpart 'single-float)
246                        (typep imagpart 'single-float))
247                   (truly-the (complex single-float)
248                              (complex realpart imagpart)))
249                  (t
250                   (%make-complex realpart imagpart)))))
251   (number-dispatch ((realpart real) (imagpart real))
252     ((rational rational)
253      (canonical-complex realpart imagpart))
254     (float-contagion %%make-complex realpart imagpart (rational)))))
255
256 (defun realpart (number)
257   #!+sb-doc
258   "Extract the real part of a number."
259   (typecase number
260     #!+long-float
261     ((complex long-float)
262      (truly-the long-float (realpart number)))
263     ((complex double-float)
264      (truly-the double-float (realpart number)))
265     ((complex single-float)
266      (truly-the single-float (realpart number)))
267     ((complex rational)
268      (sb!kernel:%realpart number))
269     (t
270      number)))
271
272 (defun imagpart (number)
273   #!+sb-doc
274   "Extract the imaginary part of a number."
275   (typecase number
276     #!+long-float
277     ((complex long-float)
278      (truly-the long-float (imagpart number)))
279     ((complex double-float)
280      (truly-the double-float (imagpart number)))
281     ((complex single-float)
282      (truly-the single-float (imagpart number)))
283     ((complex rational)
284      (sb!kernel:%imagpart number))
285     (float
286      (float 0 number))
287     (t
288      0)))
289
290 (defun conjugate (number)
291   #!+sb-doc
292   "Return the complex conjugate of NUMBER. For non-complex numbers, this is
293   an identity."
294   (if (complexp number)
295       (complex (realpart number) (- (imagpart number)))
296       number))
297
298 (defun signum (number)
299   #!+sb-doc
300   "If NUMBER is zero, return NUMBER, else return (/ NUMBER (ABS NUMBER))."
301   (if (zerop number)
302       number
303       (if (rationalp number)
304           (if (plusp number) 1 -1)
305           (/ number (abs number)))))
306 \f
307 ;;;; ratios
308
309 (defun numerator (number)
310   #!+sb-doc
311   "Return the numerator of NUMBER, which must be rational."
312   (numerator number))
313
314 (defun denominator (number)
315   #!+sb-doc
316   "Return the denominator of NUMBER, which must be rational."
317   (denominator number))
318 \f
319 ;;;; arithmetic operations
320
321 (macrolet ((define-arith (op init doc)
322              #!-sb-doc (declare (ignore doc))
323              `(defun ,op (&rest args)
324                 #!+sb-doc ,doc
325                 (if (null args) ,init
326                   (do ((args (cdr args) (cdr args))
327                        (res (car args) (,op res (car args))))
328                       ((null args) res))))))
329   (define-arith + 0
330     "Return the sum of its arguments. With no args, returns 0.")
331   (define-arith * 1
332     "Return the product of its arguments. With no args, returns 1."))
333
334 (defun - (number &rest more-numbers)
335   #!+sb-doc
336   "Subtract the second and all subsequent arguments from the first; 
337   or with one argument, negate the first argument."
338   (if more-numbers
339       (do ((nlist more-numbers (cdr nlist))
340            (result number))
341           ((atom nlist) result)
342          (declare (list nlist))
343          (setq result (- result (car nlist))))
344       (- number)))
345
346 (defun / (number &rest more-numbers)
347   #!+sb-doc
348   "Divide the first argument by each of the following arguments, in turn.
349   With one argument, return reciprocal."
350   (if more-numbers
351       (do ((nlist more-numbers (cdr nlist))
352            (result number))
353           ((atom nlist) result)
354          (declare (list nlist))
355          (setq result (/ result (car nlist))))
356       (/ number)))
357
358 (defun 1+ (number)
359   #!+sb-doc
360   "Return NUMBER + 1."
361   (1+ number))
362
363 (defun 1- (number)
364   #!+sb-doc
365   "Return NUMBER - 1."
366   (1- number))
367
368 (eval-when (:compile-toplevel)
369
370 (sb!xc:defmacro two-arg-+/- (name op big-op)
371   `(defun ,name (x y)
372      (number-dispatch ((x number) (y number))
373        (bignum-cross-fixnum ,op ,big-op)
374        (float-contagion ,op x y)
375
376        ((complex complex)
377         (canonical-complex (,op (realpart x) (realpart y))
378                            (,op (imagpart x) (imagpart y))))
379        (((foreach bignum fixnum ratio single-float double-float
380                   #!+long-float long-float) complex)
381         (complex (,op x (realpart y)) (,op (imagpart y))))
382        ((complex (or rational float))
383         (complex (,op (realpart x) y) (imagpart x)))
384
385        (((foreach fixnum bignum) ratio)
386         (let* ((dy (denominator y))
387                (n (,op (* x dy) (numerator y))))
388           (%make-ratio n dy)))
389        ((ratio integer)
390         (let* ((dx (denominator x))
391                (n (,op (numerator x) (* y dx))))
392           (%make-ratio n dx)))
393        ((ratio ratio)
394         (let* ((nx (numerator x))
395                (dx (denominator x))
396                (ny (numerator y))
397                (dy (denominator y))
398                (g1 (gcd dx dy)))
399           (if (eql g1 1)
400               (%make-ratio (,op (* nx dy) (* dx ny)) (* dx dy))
401               (let* ((t1 (,op (* nx (truncate dy g1)) (* (truncate dx g1) ny)))
402                      (g2 (gcd t1 g1))
403                      (t2 (truncate dx g1)))
404                 (cond ((eql t1 0) 0)
405                       ((eql g2 1)
406                        (%make-ratio t1 (* t2 dy)))
407                       (T (let* ((nn (truncate t1 g2))
408                                 (t3 (truncate dy g2))
409                                 (nd (if (eql t2 1) t3 (* t2 t3))))
410                            (if (eql nd 1) nn (%make-ratio nn nd))))))))))))
411
412 ); Eval-When (Compile)
413
414 (two-arg-+/- two-arg-+ + add-bignums)
415 (two-arg-+/- two-arg-- - subtract-bignum)
416
417 (defun two-arg-* (x y)
418   (flet ((integer*ratio (x y)
419            (if (eql x 0) 0
420                (let* ((ny (numerator y))
421                       (dy (denominator y))
422                       (gcd (gcd x dy)))
423                  (if (eql gcd 1)
424                      (%make-ratio (* x ny) dy)
425                      (let ((nn (* (truncate x gcd) ny))
426                            (nd (truncate dy gcd)))
427                        (if (eql nd 1)
428                            nn
429                            (%make-ratio nn nd)))))))
430          (complex*real (x y)
431            (canonical-complex (* (realpart x) y) (* (imagpart x) y))))
432     (number-dispatch ((x number) (y number))
433       (float-contagion * x y)
434
435       ((fixnum fixnum) (multiply-fixnums x y))
436       ((bignum fixnum) (multiply-bignum-and-fixnum x y))
437       ((fixnum bignum) (multiply-bignum-and-fixnum y x))
438       ((bignum bignum) (multiply-bignums x y))
439
440       ((complex complex)
441        (let* ((rx (realpart x))
442               (ix (imagpart x))
443               (ry (realpart y))
444               (iy (imagpart y)))
445          (canonical-complex (- (* rx ry) (* ix iy)) (+ (* rx iy) (* ix ry)))))
446       (((foreach bignum fixnum ratio single-float double-float
447                  #!+long-float long-float)
448         complex)
449        (complex*real y x))
450       ((complex (or rational float))
451        (complex*real x y))
452
453       (((foreach bignum fixnum) ratio) (integer*ratio x y))
454       ((ratio integer) (integer*ratio y x))
455       ((ratio ratio)
456        (let* ((nx (numerator x))
457               (dx (denominator x))
458               (ny (numerator y))
459               (dy (denominator y))
460               (g1 (gcd nx dy))
461               (g2 (gcd dx ny)))
462          (build-ratio (* (maybe-truncate nx g1)
463                          (maybe-truncate ny g2))
464                       (* (maybe-truncate dx g2)
465                          (maybe-truncate dy g1))))))))
466
467 ;;; Divide two integers, producing a canonical rational. If a fixnum,
468 ;;; we see whether they divide evenly before trying the GCD. In the
469 ;;; bignum case, we don't bother, since bignum division is expensive,
470 ;;; and the test is not very likely to succeed.
471 (defun integer-/-integer (x y)
472   (if (and (typep x 'fixnum) (typep y 'fixnum))
473       (multiple-value-bind (quo rem) (truncate x y)
474         (if (zerop rem)
475             quo
476             (let ((gcd (gcd x y)))
477               (declare (fixnum gcd))
478               (if (eql gcd 1)
479                   (build-ratio x y)
480                   (build-ratio (truncate x gcd) (truncate y gcd))))))
481       (let ((gcd (gcd x y)))
482         (if (eql gcd 1)
483             (build-ratio x y)
484             (build-ratio (truncate x gcd) (truncate y gcd))))))
485
486 (defun two-arg-/ (x y)
487   (number-dispatch ((x number) (y number))
488     (float-contagion / x y (ratio integer))
489
490     ((complex complex)
491      (let* ((rx (realpart x))
492             (ix (imagpart x))
493             (ry (realpart y))
494             (iy (imagpart y)))
495        (if (> (abs ry) (abs iy))
496            (let* ((r (/ iy ry))
497                   (dn (* ry (+ 1 (* r r)))))
498              (canonical-complex (/ (+ rx (* ix r)) dn)
499                                 (/ (- ix (* rx r)) dn)))
500            (let* ((r (/ ry iy))
501                   (dn (* iy (+ 1 (* r r)))))
502              (canonical-complex (/ (+ (* rx r) ix) dn)
503                                 (/ (- (* ix r) rx) dn))))))
504     (((foreach integer ratio single-float double-float) complex)
505      (let* ((ry (realpart y))
506             (iy (imagpart y)))
507        (if (> (abs ry) (abs iy))
508            (let* ((r (/ iy ry))
509                   (dn (* ry (+ 1 (* r r)))))
510              (canonical-complex (/ x dn)
511                                 (/ (- (* x r)) dn)))
512            (let* ((r (/ ry iy))
513                   (dn (* iy (+ 1 (* r r)))))
514              (canonical-complex (/ (* x r) dn)
515                                 (/ (- x) dn))))))
516     ((complex (or rational float))
517      (canonical-complex (/ (realpart x) y)
518                         (/ (imagpart x) y)))
519
520     ((ratio ratio)
521      (let* ((nx (numerator x))
522             (dx (denominator x))
523             (ny (numerator y))
524             (dy (denominator y))
525             (g1 (gcd nx ny))
526             (g2 (gcd dx dy)))
527        (build-ratio (* (maybe-truncate nx g1) (maybe-truncate dy g2))
528                     (* (maybe-truncate dx g2) (maybe-truncate ny g1)))))
529
530     ((integer integer)
531      (integer-/-integer x y))
532
533     ((integer ratio)
534      (if (zerop x)
535          0
536          (let* ((ny (numerator y))
537                 (dy (denominator y))
538                 (gcd (gcd x ny)))
539            (build-ratio (* (maybe-truncate x gcd) dy)
540                         (maybe-truncate ny gcd)))))
541
542     ((ratio integer)
543      (let* ((nx (numerator x))
544             (gcd (gcd nx y)))
545        (build-ratio (maybe-truncate nx gcd)
546                     (* (maybe-truncate y gcd) (denominator x)))))))
547
548 (defun %negate (n)
549   (number-dispatch ((n number))
550     (((foreach fixnum single-float double-float #!+long-float long-float))
551      (%negate n))
552     ((bignum)
553      (negate-bignum n))
554     ((ratio)
555      (%make-ratio (- (numerator n)) (denominator n)))
556     ((complex)
557      (complex (- (realpart n)) (- (imagpart n))))))
558 \f
559 ;;;; TRUNCATE and friends
560
561 (defun truncate (number &optional (divisor 1))
562   #!+sb-doc
563   "Return number (or number/divisor) as an integer, rounded toward 0.
564   The second returned value is the remainder."
565   (macrolet ((truncate-float (rtype)
566                `(let* ((float-div (coerce divisor ',rtype))
567                        (res (%unary-truncate (/ number float-div))))
568                   (values res
569                           (- number
570                              (* (coerce res ',rtype) float-div))))))
571     (number-dispatch ((number real) (divisor real))
572       ((fixnum fixnum) (truncate number divisor))
573       (((foreach fixnum bignum) ratio)
574        (let ((q (truncate (* number (denominator divisor))
575                           (numerator divisor))))
576          (values q (- number (* q divisor)))))
577       ((fixnum bignum)
578        (values 0 number))
579       ((ratio (or float rational))
580        (let ((q (truncate (numerator number)
581                           (* (denominator number) divisor))))
582          (values q (- number (* q divisor)))))
583       ((bignum fixnum)
584        (bignum-truncate number (make-small-bignum divisor)))
585       ((bignum bignum)
586        (bignum-truncate number divisor))
587
588       (((foreach single-float double-float #!+long-float long-float)
589         (or rational single-float))
590        (if (eql divisor 1)
591            (let ((res (%unary-truncate number)))
592              (values res (- number (coerce res '(dispatch-type number)))))
593            (truncate-float (dispatch-type number))))
594       #!+long-float
595       ((long-float (or single-float double-float long-float))
596        (truncate-float long-float))
597       #!+long-float
598       (((foreach double-float single-float) long-float)
599        (truncate-float long-float))
600       ((double-float (or single-float double-float))
601        (truncate-float double-float))
602       ((single-float double-float)
603        (truncate-float double-float))
604       (((foreach fixnum bignum ratio)
605         (foreach single-float double-float #!+long-float long-float))
606        (truncate-float (dispatch-type divisor))))))
607
608 ;;; Declare these guys inline to let them get optimized a little.
609 ;;; ROUND and FROUND are not declared inline since they seem too
610 ;;; obscure and too big to inline-expand by default. Also, this gives
611 ;;; the compiler a chance to pick off the unary float case. Similarly,
612 ;;; CEILING and FLOOR are only maybe-inline for now, so that the
613 ;;; power-of-2 CEILING and FLOOR transforms get a chance.
614 #!-sb-fluid (declaim (inline rem mod fceiling ffloor ftruncate))
615 (declaim (maybe-inline ceiling floor))
616
617 (defun floor (number &optional (divisor 1))
618   #!+sb-doc
619   "Return the greatest integer not greater than number, or number/divisor.
620   The second returned value is (mod number divisor)."
621   ;; If the numbers do not divide exactly and the result of
622   ;; (/ NUMBER DIVISOR) would be negative then decrement the quotient
623   ;; and augment the remainder by the divisor.
624   (multiple-value-bind (tru rem) (truncate number divisor)
625     (if (and (not (zerop rem))
626              (if (minusp divisor)
627                  (plusp number)
628                  (minusp number)))
629         (values (1- tru) (+ rem divisor))
630         (values tru rem))))
631
632 (defun ceiling (number &optional (divisor 1))
633   #!+sb-doc
634   "Return the smallest integer not less than number, or number/divisor.
635   The second returned value is the remainder."
636   ;; If the numbers do not divide exactly and the result of
637   ;; (/ NUMBER DIVISOR) would be positive then increment the quotient
638   ;; and decrement the remainder by the divisor.
639   (multiple-value-bind (tru rem) (truncate number divisor)
640     (if (and (not (zerop rem))
641              (if (minusp divisor)
642                  (minusp number)
643                  (plusp number)))
644         (values (+ tru 1) (- rem divisor))
645         (values tru rem))))
646
647 (defun round (number &optional (divisor 1))
648   #!+sb-doc
649   "Rounds number (or number/divisor) to nearest integer.
650   The second returned value is the remainder."
651   (if (eql divisor 1)
652       (round number)
653       (multiple-value-bind (tru rem) (truncate number divisor)
654         (let ((thresh (/ (abs divisor) 2)))
655           (cond ((or (> rem thresh)
656                      (and (= rem thresh) (oddp tru)))
657                  (if (minusp divisor)
658                      (values (- tru 1) (+ rem divisor))
659                      (values (+ tru 1) (- rem divisor))))
660                 ((let ((-thresh (- thresh)))
661                    (or (< rem -thresh)
662                        (and (= rem -thresh) (oddp tru))))
663                  (if (minusp divisor)
664                      (values (+ tru 1) (- rem divisor))
665                      (values (- tru 1) (+ rem divisor))))
666                 (t (values tru rem)))))))
667
668 (defun rem (number divisor)
669   #!+sb-doc
670   "Return second result of TRUNCATE."
671   (multiple-value-bind (tru rem) (truncate number divisor)
672     (declare (ignore tru))
673     rem))
674
675 (defun mod (number divisor)
676   #!+sb-doc
677   "Return second result of FLOOR."
678   (let ((rem (rem number divisor)))
679     (if (and (not (zerop rem))
680              (if (minusp divisor)
681                  (plusp number)
682                  (minusp number)))
683         (+ rem divisor)
684         rem)))
685
686 (macrolet ((def (name op doc)
687              `(defun ,name (number &optional (divisor 1))
688                 ,doc
689                 (multiple-value-bind (res rem) (,op number divisor)
690                   (values (float res (if (floatp rem) rem 1.0)) rem)))))
691   (def ffloor floor
692     "Same as FLOOR, but returns first value as a float.")
693   (def fceiling ceiling
694     "Same as CEILING, but returns first value as a float." )
695   (def ftruncate truncate
696     "Same as TRUNCATE, but returns first value as a float.")
697   (def fround round
698     "Same as ROUND, but returns first value as a float."))
699 \f
700 ;;;; comparisons
701
702 (defun = (number &rest more-numbers)
703   #!+sb-doc
704   "Return T if all of its arguments are numerically equal, NIL otherwise."
705   (do ((nlist more-numbers (cdr nlist)))
706       ((atom nlist) T)
707      (declare (list nlist))
708      (if (not (= (car nlist) number)) (return nil))))
709
710 (defun /= (number &rest more-numbers)
711   #!+sb-doc
712   "Return T if no two of its arguments are numerically equal, NIL otherwise."
713   (do* ((head number (car nlist))
714         (nlist more-numbers (cdr nlist)))
715        ((atom nlist) t)
716      (declare (list nlist))
717      (unless (do* ((nl nlist (cdr nl)))
718                   ((atom nl) T)
719                (declare (list nl))
720                (if (= head (car nl)) (return nil)))
721        (return nil))))
722
723 (defun < (number &rest more-numbers)
724   #!+sb-doc
725   "Return T if its arguments are in strictly increasing order, NIL otherwise."
726   (do* ((n number (car nlist))
727         (nlist more-numbers (cdr nlist)))
728        ((atom nlist) t)
729      (declare (list nlist))
730      (if (not (< n (car nlist))) (return nil))))
731
732 (defun > (number &rest more-numbers)
733   #!+sb-doc
734   "Return T if its arguments are in strictly decreasing order, NIL otherwise."
735   (do* ((n number (car nlist))
736         (nlist more-numbers (cdr nlist)))
737        ((atom nlist) t)
738      (declare (list nlist))
739      (if (not (> n (car nlist))) (return nil))))
740
741 (defun <= (number &rest more-numbers)
742   #!+sb-doc
743   "Return T if arguments are in strictly non-decreasing order, NIL otherwise."
744   (do* ((n number (car nlist))
745         (nlist more-numbers (cdr nlist)))
746        ((atom nlist) t)
747      (declare (list nlist))
748      (if (not (<= n (car nlist))) (return nil))))
749
750 (defun >= (number &rest more-numbers)
751   #!+sb-doc
752   "Return T if arguments are in strictly non-increasing order, NIL otherwise."
753   (do* ((n number (car nlist))
754         (nlist more-numbers (cdr nlist)))
755        ((atom nlist) t)
756      (declare (list nlist))
757      (if (not (>= n (car nlist))) (return nil))))
758
759 (defun max (number &rest more-numbers)
760   #!+sb-doc
761   "Return the greatest of its arguments."
762   (do ((nlist more-numbers (cdr nlist))
763        (result number))
764       ((null nlist) (return result))
765      (declare (list nlist))
766      (if (> (car nlist) result) (setq result (car nlist)))))
767
768 (defun min (number &rest more-numbers)
769   #!+sb-doc
770   "Return the least of its arguments."
771   (do ((nlist more-numbers (cdr nlist))
772        (result number))
773       ((null nlist) (return result))
774      (declare (list nlist))
775      (if (< (car nlist) result) (setq result (car nlist)))))
776
777 (eval-when (:compile-toplevel :execute)
778
779 ;;; The INFINITE-X-FINITE-Y and INFINITE-Y-FINITE-X args tell us how
780 ;;; to handle the case when X or Y is a floating-point infinity and
781 ;;; the other arg is a rational. (Section 12.1.4.1 of the ANSI spec
782 ;;; says that comparisons are done by converting the float to a
783 ;;; rational when comparing with a rational, but infinities can't be
784 ;;; converted to a rational, so we show some initiative and do it this
785 ;;; way instead.)
786 (defun basic-compare (op &key infinite-x-finite-y infinite-y-finite-x)
787   `(((fixnum fixnum) (,op x y))
788
789     ((single-float single-float) (,op x y))
790     #!+long-float
791     (((foreach single-float double-float long-float) long-float)
792      (,op (coerce x 'long-float) y))
793     #!+long-float
794     ((long-float (foreach single-float double-float))
795      (,op x (coerce y 'long-float)))
796     (((foreach single-float double-float) double-float)
797      (,op (coerce x 'double-float) y))
798     ((double-float single-float)
799      (,op x (coerce y 'double-float)))
800     (((foreach single-float double-float #!+long-float long-float) rational)
801      (if (eql y 0)
802          (,op x (coerce 0 '(dispatch-type x)))
803          (if (float-infinity-p x)
804              ,infinite-x-finite-y
805              (,op (rational x) y))))
806     (((foreach bignum fixnum ratio) float)
807      (if (float-infinity-p y)
808          ,infinite-y-finite-x
809          (,op x (rational y))))))
810 ) ; EVAL-WHEN
811
812 (macrolet ((def-two-arg-</> (name op ratio-arg1 ratio-arg2 &rest cases)
813              `(defun ,name (x y)
814                 (number-dispatch ((x real) (y real))
815                                  (basic-compare
816                                   ,op
817                                   :infinite-x-finite-y
818                                   (,op x (coerce 0 '(dispatch-type x)))
819                                   :infinite-y-finite-x
820                                   (,op (coerce 0 '(dispatch-type y)) y))
821                                  (((foreach fixnum bignum) ratio)
822                                   (,op x (,ratio-arg2 (numerator y)
823                                                       (denominator y))))
824                                  ((ratio integer)
825                                   (,op (,ratio-arg1 (numerator x)
826                                                     (denominator x))
827                                        y))
828                                  ((ratio ratio)
829                                   (,op (* (numerator   (truly-the ratio x))
830                                           (denominator (truly-the ratio y)))
831                                        (* (numerator   (truly-the ratio y))
832                                           (denominator (truly-the ratio x)))))
833                                  ,@cases))))
834   (def-two-arg-</> two-arg-< < floor ceiling
835     ((fixnum bignum)
836      (bignum-plus-p y))
837     ((bignum fixnum)
838      (not (bignum-plus-p x)))
839     ((bignum bignum)
840      (minusp (bignum-compare x y))))
841   (def-two-arg-</> two-arg-> > ceiling floor
842     ((fixnum bignum)
843      (not (bignum-plus-p y)))
844     ((bignum fixnum)
845      (bignum-plus-p x))
846     ((bignum bignum)
847      (plusp (bignum-compare x y)))))
848
849 (defun two-arg-= (x y)
850   (number-dispatch ((x number) (y number))
851     (basic-compare =
852                    ;; An infinite value is never equal to a finite value.
853                    :infinite-x-finite-y nil
854                    :infinite-y-finite-x nil)
855     ((fixnum (or bignum ratio)) nil)
856
857     ((bignum (or fixnum ratio)) nil)
858     ((bignum bignum)
859      (zerop (bignum-compare x y)))
860
861     ((ratio integer) nil)
862     ((ratio ratio)
863      (and (eql (numerator x) (numerator y))
864           (eql (denominator x) (denominator y))))
865
866     ((complex complex)
867      (and (= (realpart x) (realpart y))
868           (= (imagpart x) (imagpart y))))
869     (((foreach fixnum bignum ratio single-float double-float
870                #!+long-float long-float) complex)
871      (and (= x (realpart y))
872           (zerop (imagpart y))))
873     ((complex (or float rational))
874      (and (= (realpart x) y)
875           (zerop (imagpart x))))))
876
877 (defun eql (obj1 obj2)
878   #!+sb-doc
879   "Return T if OBJ1 and OBJ2 represent the same object, otherwise NIL."
880   (or (eq obj1 obj2)
881       (if (or (typep obj2 'fixnum)
882               (not (typep obj2 'number)))
883           nil
884           (macrolet ((foo (&rest stuff)
885                        `(typecase obj2
886                           ,@(mapcar (lambda (foo)
887                                       (let ((type (car foo))
888                                             (fn (cadr foo)))
889                                         `(,type
890                                           (and (typep obj1 ',type)
891                                                (,fn obj1 obj2)))))
892                                     stuff))))
893             (foo
894               (single-float eql)
895               (double-float eql)
896               #!+long-float
897               (long-float eql)
898               (bignum
899                (lambda (x y)
900                  (zerop (bignum-compare x y))))
901               (ratio
902                (lambda (x y)
903                  (and (eql (numerator x) (numerator y))
904                       (eql (denominator x) (denominator y)))))
905               (complex
906                (lambda (x y)
907                  (and (eql (realpart x) (realpart y))
908                       (eql (imagpart x) (imagpart y))))))))))
909 \f
910 ;;;; logicals
911
912 (defun logior (&rest integers)
913   #!+sb-doc
914   "Return the bit-wise or of its arguments. Args must be integers."
915   (declare (list integers))
916   (if integers
917       (do ((result (pop integers) (logior result (pop integers))))
918           ((null integers) result))
919       0))
920
921 (defun logxor (&rest integers)
922   #!+sb-doc
923   "Return the bit-wise exclusive or of its arguments. Args must be integers."
924   (declare (list integers))
925   (if integers
926       (do ((result (pop integers) (logxor result (pop integers))))
927           ((null integers) result))
928       0))
929
930 (defun logand (&rest integers)
931   #!+sb-doc
932   "Return the bit-wise and of its arguments. Args must be integers."
933   (declare (list integers))
934   (if integers
935       (do ((result (pop integers) (logand result (pop integers))))
936           ((null integers) result))
937       -1))
938
939 (defun logeqv (&rest integers)
940   #!+sb-doc
941   "Return the bit-wise equivalence of its arguments. Args must be integers."
942   (declare (list integers))
943   (if integers
944       (do ((result (pop integers) (logeqv result (pop integers))))
945           ((null integers) result))
946       -1))
947
948 (defun lognand (integer1 integer2)
949   #!+sb-doc
950   "Return the complement of the logical AND of integer1 and integer2."
951   (lognand integer1 integer2))
952
953 (defun lognor (integer1 integer2)
954   #!+sb-doc
955   "Return the complement of the logical OR of integer1 and integer2."
956   (lognor integer1 integer2))
957
958 (defun logandc1 (integer1 integer2)
959   #!+sb-doc
960   "Return the logical AND of (LOGNOT integer1) and integer2."
961   (logandc1 integer1 integer2))
962
963 (defun logandc2 (integer1 integer2)
964   #!+sb-doc
965   "Return the logical AND of integer1 and (LOGNOT integer2)."
966   (logandc2 integer1 integer2))
967
968 (defun logorc1 (integer1 integer2)
969   #!+sb-doc
970   "Return the logical OR of (LOGNOT integer1) and integer2."
971   (logorc1 integer1 integer2))
972
973 (defun logorc2 (integer1 integer2)
974   #!+sb-doc
975   "Return the logical OR of integer1 and (LOGNOT integer2)."
976   (logorc2 integer1 integer2))
977
978 (defun lognot (number)
979   #!+sb-doc
980   "Return the bit-wise logical not of integer."
981   (etypecase number
982     (fixnum (lognot (truly-the fixnum number)))
983     (bignum (bignum-logical-not number))))
984
985 (macrolet ((def (name op big-op)
986              `(defun ,name (x y)
987                (number-dispatch ((x integer) (y integer))
988                  (bignum-cross-fixnum ,op ,big-op)))))
989   (def two-arg-and logand bignum-logical-and)
990   (def two-arg-ior logior bignum-logical-ior)
991   (def two-arg-xor logxor bignum-logical-xor))
992
993 (defun logcount (integer)
994   #!+sb-doc
995   "Count the number of 1 bits if INTEGER is positive, and the number of 0 bits
996   if INTEGER is negative."
997   (etypecase integer
998     (fixnum
999      (logcount (truly-the (integer 0 #.(max most-positive-fixnum
1000                                             (lognot most-negative-fixnum)))
1001                           (if (minusp (truly-the fixnum integer))
1002                               (lognot (truly-the fixnum integer))
1003                               integer))))
1004     (bignum
1005      (bignum-logcount integer))))
1006
1007 (defun logtest (integer1 integer2)
1008   #!+sb-doc
1009   "Predicate which returns T if logand of integer1 and integer2 is not zero."
1010   (logtest integer1 integer2))
1011
1012 (defun logbitp (index integer)
1013   #!+sb-doc
1014   "Predicate returns T if bit index of integer is a 1."
1015   (logbitp index integer))
1016
1017 (defun ash (integer count)
1018   #!+sb-doc
1019   "Shifts integer left by count places preserving sign. - count shifts right."
1020   (declare (integer integer count))
1021   (etypecase integer
1022     (fixnum
1023      (cond ((zerop integer)
1024             0)
1025            ((fixnump count)
1026             (let ((length (integer-length (truly-the fixnum integer)))
1027                   (count (truly-the fixnum count)))
1028               (declare (fixnum length count))
1029               (cond ((and (plusp count)
1030                           (> (+ length count)
1031                              (integer-length most-positive-fixnum)))
1032                      (bignum-ashift-left (make-small-bignum integer) count))
1033                     (t
1034                      (truly-the fixnum
1035                                 (ash (truly-the fixnum integer) count))))))
1036            ((minusp count)
1037             (if (minusp integer) -1 0))
1038            (t
1039             (bignum-ashift-left (make-small-bignum integer) count))))
1040     (bignum
1041      (if (plusp count)
1042          (bignum-ashift-left integer count)
1043          (bignum-ashift-right integer (- count))))))
1044
1045 (defun integer-length (integer)
1046   #!+sb-doc
1047   "Return the number of significant bits in the absolute value of integer."
1048   (etypecase integer
1049     (fixnum
1050      (integer-length (truly-the fixnum integer)))
1051     (bignum
1052      (bignum-integer-length integer))))
1053 \f
1054 ;;;; BYTE, bytespecs, and related operations
1055
1056 (defun byte (size position)
1057   #!+sb-doc
1058   "Return a byte specifier which may be used by other byte functions
1059   (e.g. LDB)."
1060   (byte size position))
1061
1062 (defun byte-size (bytespec)
1063   #!+sb-doc
1064   "Return the size part of the byte specifier bytespec."
1065   (byte-size bytespec))
1066
1067 (defun byte-position (bytespec)
1068   #!+sb-doc
1069   "Return the position part of the byte specifier bytespec."
1070   (byte-position bytespec))
1071
1072 (defun ldb (bytespec integer)
1073   #!+sb-doc
1074   "Extract the specified byte from integer, and right justify result."
1075   (ldb bytespec integer))
1076
1077 (defun ldb-test (bytespec integer)
1078   #!+sb-doc
1079   "Return T if any of the specified bits in integer are 1's."
1080   (ldb-test bytespec integer))
1081
1082 (defun mask-field (bytespec integer)
1083   #!+sb-doc
1084   "Extract the specified byte from integer,  but do not right justify result."
1085   (mask-field bytespec integer))
1086
1087 (defun dpb (newbyte bytespec integer)
1088   #!+sb-doc
1089   "Return new integer with newbyte in specified position, newbyte is right justified."
1090   (dpb newbyte bytespec integer))
1091
1092 (defun deposit-field (newbyte bytespec integer)
1093   #!+sb-doc
1094   "Return new integer with newbyte in specified position, newbyte is not right justified."
1095   (deposit-field newbyte bytespec integer))
1096
1097 (defun %ldb (size posn integer)
1098   (logand (ash integer (- posn))
1099           (1- (ash 1 size))))
1100
1101 (defun %mask-field (size posn integer)
1102   (logand integer (ash (1- (ash 1 size)) posn)))
1103
1104 (defun %dpb (newbyte size posn integer)
1105   (let ((mask (1- (ash 1 size))))
1106     (logior (logand integer (lognot (ash mask posn)))
1107             (ash (logand newbyte mask) posn))))
1108
1109 (defun %deposit-field (newbyte size posn integer)
1110   (let ((mask (ash (ldb (byte size 0) -1) posn)))
1111     (logior (logand newbyte mask)
1112             (logand integer (lognot mask)))))
1113 \f
1114 ;;;; BOOLE
1115
1116 ;;; The boole function dispaches to any logic operation depending on
1117 ;;;     the value of a variable. Presently, legal selector values are [0..15].
1118 ;;;     boole is open coded for calls with a constant selector. or with calls
1119 ;;;     using any of the constants declared below.
1120
1121 (defconstant boole-clr 0
1122   #!+sb-doc
1123   "Boole function op, makes BOOLE return 0.")
1124
1125 (defconstant boole-set 1
1126   #!+sb-doc
1127   "Boole function op, makes BOOLE return -1.")
1128
1129 (defconstant boole-1   2
1130   #!+sb-doc
1131   "Boole function op, makes BOOLE return integer1.")
1132
1133 (defconstant boole-2   3
1134   #!+sb-doc
1135   "Boole function op, makes BOOLE return integer2.")
1136
1137 (defconstant boole-c1  4
1138   #!+sb-doc
1139   "Boole function op, makes BOOLE return complement of integer1.")
1140
1141 (defconstant boole-c2  5
1142   #!+sb-doc
1143   "Boole function op, makes BOOLE return complement of integer2.")
1144
1145 (defconstant boole-and 6
1146   #!+sb-doc
1147   "Boole function op, makes BOOLE return logand of integer1 and integer2.")
1148
1149 (defconstant boole-ior 7
1150   #!+sb-doc
1151   "Boole function op, makes BOOLE return logior of integer1 and integer2.")
1152
1153 (defconstant boole-xor 8
1154   #!+sb-doc
1155   "Boole function op, makes BOOLE return logxor of integer1 and integer2.")
1156
1157 (defconstant boole-eqv 9
1158   #!+sb-doc
1159   "Boole function op, makes BOOLE return logeqv of integer1 and integer2.")
1160
1161 (defconstant boole-nand  10
1162   #!+sb-doc
1163   "Boole function op, makes BOOLE return log nand of integer1 and integer2.")
1164
1165 (defconstant boole-nor   11
1166   #!+sb-doc
1167   "Boole function op, makes BOOLE return lognor of integer1 and integer2.")
1168
1169 (defconstant boole-andc1 12
1170   #!+sb-doc
1171   "Boole function op, makes BOOLE return logandc1 of integer1 and integer2.")
1172
1173 (defconstant boole-andc2 13
1174   #!+sb-doc
1175   "Boole function op, makes BOOLE return logandc2 of integer1 and integer2.")
1176
1177 (defconstant boole-orc1  14
1178   #!+sb-doc
1179   "Boole function op, makes BOOLE return logorc1 of integer1 and integer2.")
1180
1181 (defconstant boole-orc2  15
1182   #!+sb-doc
1183   "Boole function op, makes BOOLE return logorc2 of integer1 and integer2.")
1184
1185 (defun boole (op integer1 integer2)
1186   #!+sb-doc
1187   "Bit-wise boolean function on two integers. Function chosen by OP:
1188         0       BOOLE-CLR
1189         1       BOOLE-SET
1190         2       BOOLE-1
1191         3       BOOLE-2
1192         4       BOOLE-C1
1193         5       BOOLE-C2
1194         6       BOOLE-AND
1195         7       BOOLE-IOR
1196         8       BOOLE-XOR
1197         9       BOOLE-EQV
1198         10      BOOLE-NAND
1199         11      BOOLE-NOR
1200         12      BOOLE-ANDC1
1201         13      BOOLE-ANDC2
1202         14      BOOLE-ORC1
1203         15      BOOLE-ORC2"
1204   (case op
1205     (0 (boole 0 integer1 integer2))
1206     (1 (boole 1 integer1 integer2))
1207     (2 (boole 2 integer1 integer2))
1208     (3 (boole 3 integer1 integer2))
1209     (4 (boole 4 integer1 integer2))
1210     (5 (boole 5 integer1 integer2))
1211     (6 (boole 6 integer1 integer2))
1212     (7 (boole 7 integer1 integer2))
1213     (8 (boole 8 integer1 integer2))
1214     (9 (boole 9 integer1 integer2))
1215     (10 (boole 10 integer1 integer2))
1216     (11 (boole 11 integer1 integer2))
1217     (12 (boole 12 integer1 integer2))
1218     (13 (boole 13 integer1 integer2))
1219     (14 (boole 14 integer1 integer2))
1220     (15 (boole 15 integer1 integer2))
1221     (t (error 'type-error :datum op :expected-type '(mod 16)))))
1222 \f
1223 ;;;; GCD and LCM
1224
1225 (defun gcd (&rest numbers)
1226   #!+sb-doc
1227   "Return the greatest common divisor of the arguments, which must be
1228   integers. Gcd with no arguments is defined to be 0."
1229   (cond ((null numbers) 0)
1230         ((null (cdr numbers)) (abs (the integer (car numbers))))
1231         (t
1232          (do ((gcd (the integer (car numbers))
1233                    (gcd gcd (the integer (car rest))))
1234               (rest (cdr numbers) (cdr rest)))
1235              ((null rest) gcd)
1236            (declare (integer gcd)
1237                     (list rest))))))
1238
1239 (defun lcm (&rest numbers)
1240   #!+sb-doc
1241   "Return the least common multiple of one or more integers. LCM of no
1242   arguments is defined to be 1."
1243   (cond ((null numbers) 1)
1244         ((null (cdr numbers)) (abs (the integer (car numbers))))
1245         (t
1246          (do ((lcm (the integer (car numbers))
1247                    (lcm lcm (the integer (car rest))))
1248               (rest (cdr numbers) (cdr rest)))
1249              ((null rest) lcm)
1250            (declare (integer lcm) (list rest))))))
1251
1252 (defun two-arg-lcm (n m)
1253   (declare (integer n m))
1254   (* (truncate (max n m) (gcd n m)) (min n m)))
1255
1256 ;;; Do the GCD of two integer arguments. With fixnum arguments, we use the
1257 ;;; binary GCD algorithm from Knuth's seminumerical algorithms (slightly
1258 ;;; structurified), otherwise we call BIGNUM-GCD. We pick off the special case
1259 ;;; of 0 before the dispatch so that the bignum code doesn't have to worry
1260 ;;; about "small bignum" zeros.
1261 (defun two-arg-gcd (u v)
1262   (cond ((eql u 0) v)
1263         ((eql v 0) u)
1264         (t
1265          (number-dispatch ((u integer) (v integer))
1266            ((fixnum fixnum)
1267             (locally
1268               (declare (optimize (speed 3) (safety 0)))
1269               (do ((k 0 (1+ k))
1270                    (u (abs u) (ash u -1))
1271                    (v (abs v) (ash v -1)))
1272                   ((oddp (logior u v))
1273                    (do ((temp (if (oddp u) (- v) (ash u -1))
1274                               (ash temp -1)))
1275                        (nil)
1276                      (declare (fixnum temp))
1277                      (when (oddp temp)
1278                        (if (plusp temp)
1279                            (setq u temp)
1280                            (setq v (- temp)))
1281                        (setq temp (- u v))
1282                        (when (zerop temp)
1283                          (let ((res (ash u k)))
1284                            (declare (type (signed-byte 31) res)
1285                                     (optimize (inhibit-warnings 3)))
1286                            (return res))))))
1287                 (declare (type (mod 30) k)
1288                          (type (signed-byte 31) u v)))))
1289            ((bignum bignum)
1290             (bignum-gcd u v))
1291            ((bignum fixnum)
1292             (bignum-gcd u (make-small-bignum v)))
1293            ((fixnum bignum)
1294             (bignum-gcd (make-small-bignum u) v))))))
1295 \f
1296 ;;; From discussion on comp.lang.lisp and Akira Kurihara.
1297 (defun isqrt (n)
1298   #!+sb-doc
1299   "Return the root of the nearest integer less than n which is a perfect
1300    square."
1301   (declare (type unsigned-byte n) (values unsigned-byte))
1302   ;; Theoretically (> n 7), i.e., n-len-quarter > 0.
1303   (if (and (fixnump n) (<= n 24))
1304       (cond ((> n 15) 4)
1305             ((> n  8) 3)
1306             ((> n  3) 2)
1307             ((> n  0) 1)
1308             (t 0))
1309       (let* ((n-len-quarter (ash (integer-length n) -2))
1310              (n-half (ash n (- (ash n-len-quarter 1))))
1311              (n-half-isqrt (isqrt n-half))
1312              (init-value (ash (1+ n-half-isqrt) n-len-quarter)))
1313         (loop
1314           (let ((iterated-value
1315                  (ash (+ init-value (truncate n init-value)) -1)))
1316             (unless (< iterated-value init-value)
1317               (return init-value))
1318             (setq init-value iterated-value))))))
1319 \f
1320 ;;;; miscellaneous number predicates
1321
1322 (macrolet ((def (name doc)
1323              `(defun ,name (number) ,doc (,name number))))
1324   (def zerop "Is this number zero?")
1325   (def plusp "Is this real number strictly positive?")
1326   (def minusp "Is this real number strictly negative?")
1327   (def oddp "Is this integer odd?")
1328   (def evenp "Is this integer even?"))