Created
January 9, 2015 20:32
-
-
Save igorw/695a9300b0f490d1d7c5 to your computer and use it in GitHub Desktop.
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 divmod.core) | |
; division by repeated subtraction | |
; http://en.wikipedia.org/wiki/Division_algorithm#Division_by_repeated_subtraction | |
(defn divmod | |
[n d] | |
(cond | |
(= d 0) (throw (Throwable. "Division By Zero")) | |
(< d 0) | |
(let [[q r] (divmod n (- d))] | |
[(- q) r]) | |
(< n 0) | |
(let [[q r] (divmod (- n) d)] | |
(if (= r 0) | |
[(- q) 0]) | |
[(dec (- q)) (- d r)]) | |
:else | |
(loop [q 0 | |
r n] | |
(if (< r d) | |
[q r] | |
(recur (inc q) (- r d)))))) | |
; (use 'divmod.core :reload) | |
; (divmod 1 1) | |
;=> [1 0] | |
; (divmod 1 2) | |
;=> [0 1] | |
; (divmod 20 5) | |
;=> [4 0] | |
; (divmod 5 20) | |
; [0 5] | |
; (divmod 5 4) | |
;=> [1 1] | |
; (divmod 1000000 0) | |
;=> #<Throwable java.lang.Throwable: Division By Zero> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment