Skip to content

Instantly share code, notes, and snippets.

@baioc
Last active October 4, 2019 12:19
Show Gist options
  • Save baioc/7753c8e20319d52efe475230d2dce06b to your computer and use it in GitHub Desktop.
Save baioc/7753c8e20319d52efe475230d2dce06b to your computer and use it in GitHub Desktop.
Russian Peasant Multiplication Scheme
;; Egyptian / Russian peasant multiplication in O(lg(n))
(define (times b n)
(define (iter b n sum)
(cond ((= n 0) sum)
((even? n) (iter (double b) (halve n) sum))
(else (iter b (- n 1) (+ b sum)))))
(if (< n 0)
(iter (- b) (- n) 0)
(iter b n 0)))
(define (double x) (ash x 1))
(define (halve x) (ash x -1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment