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