Alex Rivera | Logout

How to do exponentiation in clojure?

Asked 2011-02-20T12:32:19.697
133

How can I do exponentiation in clojure? For now I'm only needing integer exponentiation, but the question goes for fractions too.

Edit
Report

2 Answers

159

classic recursion (watch this, it blows stack)

(defn exp [x n]
     (if (zero? n) 1
         (* x (exp x (dec n)))))

tail recursion

(defn exp [x n]
  (loop [acc 1 n n]
    (if (zero? n) acc
        (recur (* x acc) (dec n)))))

functional

(defn exp [x n]
  (reduce * (repeat n x)))

sneaky (also blows stack, but not so easily)

(defn exp-s [x n]
  (let [square (fn[x] (* x x))]
    (cond (zero? n) 1
          (even? n) (square (exp-s x (/ n 2)))
          :else (* x (exp-s x (dec n))))))

library

(require 'clojure.contrib.math)
answered 2011-02-20T17:07:02.250
15

When this question was originally asked, clojure.contrib.math/expt was the official library function to do this. Since then, it has moved to clojure.math.numeric-tower

answered 2011-02-20T17:00:30.417

Your Answer