Created
February 6, 2016 13:32
-
-
Save guysmoilov/41b7eca9d47be4740cd2 to your computer and use it in GitHub Desktop.
Effficient exponent function in Clojure
This file contains hidden or 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
(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