Skip to content

Instantly share code, notes, and snippets.

@jasonsperske
Created December 5, 2013 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonsperske/7798178 to your computer and use it in GitHub Desktop.
Save jasonsperske/7798178 to your computer and use it in GitHub Desktop.
I wanted to try and apply what I have learned writing a JavaScript implementation of the Russian Peasant Algorithm to what I have been learning with Scheme. This works the same way as the JavaScript function :)
(ns Russian)
(defn multiply [& args]
(defn russian_multiply [a b p]
(cond
(> a 0) (russian_multiply (bit-shift-right a 1) (bit-shift-left b 1) (+ p (if (= (mod a 2) 1) b 0)))
:else p))
(defn flip [a] (inc (bit-not a)))
(let [f (first args), r (rest args)]
(let [s (count r)]
(cond
(> s 0)
(if (neg? f)
(flip (apply multiply (cons (russian_multiply (flip f) (first r) 0) (rest r))))
(apply multiply (cons (russian_multiply f (first r) 0) (rest r))))
:else f)
)
)
)
;And to use it:
;=> (multiply 2 5 -2)
;-20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment