How to do exponentiation in clojure?

Peter picture Peter · Feb 20, 2011 · Viewed 45.9k times · Source

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

Answer

John Lawrence Aspden picture John Lawrence Aspden · Feb 20, 2011

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)