Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Effficient exponent function in Clojure
(defn exp
"exponent of x^n (int n only), with tail recursion and O(logn)"
[x n]
(if (< n 0)
(/ 1 (exp x (- n)))
(loop [acc 1
base x
pow n]
(if (= pow 0)
acc
(if (even? pow)
(recur acc (* base base) (/ pow 2))
(recur (* acc base) base (dec pow)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment