Skip to content

Instantly share code, notes, and snippets.

@igorw
Created January 9, 2015 20:32
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 igorw/695a9300b0f490d1d7c5 to your computer and use it in GitHub Desktop.
Save igorw/695a9300b0f490d1d7c5 to your computer and use it in GitHub Desktop.
(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