Skip to content

Instantly share code, notes, and snippets.

@manishym
Created January 21, 2012 01:33
Show Gist options
  • Save manishym/1650669 to your computer and use it in GitHub Desktop.
Save manishym/1650669 to your computer and use it in GitHub Desktop.
Multiplication using iterative addition
(defun double (n)
(+ n n))
(defun halve (n)
(/ n 2))
;;; Normal
(defun mul (a b)
(if (= b 1)
a
(+ a (mul a (- b 1)))))
;;; log
;; ex 1.17
(defun mul-log (a b)
(if (= b 1)
a
(if (evenp b)
(double (mul-log a (halve b)))
(+ a (mul-log a (- b 1))))))
;;; iterative
;; ex 1.18
(defun mul-log-iter (a b)
(labels (
(iter (acc a b)
;; (format t "~& ACC: ~A ~& A: ~A ~&B: ~A ~& ACC+(a * b) :~A" acc a b (+ acc (* a b)) )
(cond ((= b 1) (+ acc a))
((evenp b) (iter acc (double a) (halve b)))
(t (iter (+ acc a) a (- b 1))))))
(iter 0 a b)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment