Skip to content

Instantly share code, notes, and snippets.

@aoeuidht
Created October 30, 2012 07:45
Show Gist options
  • Save aoeuidht/3978843 to your computer and use it in GitHub Desktop.
Save aoeuidht/3978843 to your computer and use it in GitHub Desktop.
SICP Exercise 1.17 -- fast-times
; Now suppose we include, together with addition,
; operations double, which doubles an integer,
; and halve, which divides an (even) integer by 2.
; Using these, design a multiplication procedure analogous to
; fast-expt that uses a logarithmic number of steps.
(defun fast_times (multiplicand multiplier)
(cond ((= multiplier 0) 0)
((even? multiplier)
(double (fast_times multiplicand (half multiplier))))
(else
(+ multiplicand (fast_times multiplicand (- multiplier 1))))))
@porcow
Copy link

porcow commented Nov 1, 2012

My solution:

(define (fast-multi a b)
  (define (double x)
    (+ x x))
  (define (halve x)
    (/ x 2))
  (define (even? n)
    (= (remainder n 2) 0))
  (define (multi-iter a b r)
    (cond ((= b 0) r)
          ((even? b) (multi-iter (double a) (halve b) r))
          (else (multi-iter a (- b 1) (+ r a)))))
  (multi-iter a b 0))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment