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