Created
December 5, 2013 00:31
-
-
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 :)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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