]> git.eshelyaron.com Git - emacs.git/commitdiff
Calc: simplify integer log2 and power of 2
authorMattias Engdegård <mattiase@acm.org>
Mon, 7 Dec 2020 09:15:59 +0000 (10:15 +0100)
committerMattias Engdegård <mattiase@acm.org>
Mon, 7 Dec 2020 12:18:00 +0000 (13:18 +0100)
We have bignums and fast primitives now; no caches are needed.

* lisp/calc/calc-bin.el (math-power-of-2-cache)
(math-big-power-of-2-cache): Remove.
(math-power-of-2, math-integer-log2): Simplify.
(calcFunc-ash): Don't call math-power-of-2 with negative argument.

lisp/calc/calc-bin.el

index e3b1013b9aaa441bc1e26f73b5389d77925f7199..6d93587234802f4ca61227556bd9fa761b765c42 100644 (file)
      (message "Omitting leading zeros on integers"))))
 
 
-(defvar math-power-of-2-cache (list 1 2 4 8 16 32 64 128 256 512 1024))
-(defvar math-big-power-of-2-cache nil)
 (defun math-power-of-2 (n)    ;  [I I] [Public]
-  (if (and (natnump n) (<= n 100))
-      (or (nth n math-power-of-2-cache)
-         (let* ((i (length math-power-of-2-cache))
-                (val (nth (1- i) math-power-of-2-cache)))
-           (while (<= i n)
-             (setq val (math-mul val 2)
-                   math-power-of-2-cache (nconc math-power-of-2-cache
-                                                (list val))
-                   i (1+ i)))
-           val))
-    (let ((found (assq n math-big-power-of-2-cache)))
-      (if found
-         (cdr found)
-       (let ((po2 (math-ipow 2 n)))
-         (setq math-big-power-of-2-cache
-               (cons (cons n po2) math-big-power-of-2-cache))
-         po2)))))
+  (if (natnump n)
+      (ash 1 n)
+    (error "argument must be a natural number")))
 
 (defun math-integer-log2 (n)    ; [I I] [Public]
-  (let ((i 0)
-       (p math-power-of-2-cache)
-       val)
-    (while (and p (< (setq val (car p)) n))
-      (setq p (cdr p)
-           i (1+ i)))
-    (if p
-       (and (equal val n)
-            i)
-      (while (<
-             (prog1
-                 (setq val (math-mul val 2))
-               (setq math-power-of-2-cache (nconc math-power-of-2-cache
-                                                  (list val))))
-             n)
-       (setq i (1+ i)))
-      (and (equal val n)
-          i))))
-
-
+  (and (natnump n)
+       (not (zerop n))
+       (zerop (logand n (1- n)))
+       (logb n)))
 
 
 ;;; Bitwise operations.
          (math-clip (calcFunc-ash a n (- w)) w)
        (if (Math-integer-negp a)
            (setq a (math-clip a w)))
-       (let ((two-to-sizem1 (math-power-of-2 (1- w)))
+       (let ((two-to-sizem1 (and (not (zerop w)) (math-power-of-2 (1- w))))
              (sh (calcFunc-lsh a n w)))
          (cond ((or (zerop w)
                      (zerop (logand a two-to-sizem1)))