Skip to content

Instantly share code, notes, and snippets.

@guysmoilov
Created February 6, 2016 13:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guysmoilov/41b7eca9d47be4740cd2 to your computer and use it in GitHub Desktop.
Save guysmoilov/41b7eca9d47be4740cd2 to your computer and use it in GitHub Desktop.
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