How to do exponentiation in clojure?

前端 未结 13 1826
执笔经年
执笔经年 2021-01-30 12:32

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

13条回答
  •  长情又很酷
    2021-01-30 12:34

    Try

    (defn pow [x n]
      (loop [x x n n r 1]
        (cond
          (= n 0) r
          (even? n) (recur (* x x) (/ n 2) r)
          :else (recur x (dec n) (* r x)))))
    

    for a tail-recursive O(log n) solution, if you want to implement it yourself (only supports positive integers). Obviously, the better solution is to use the library functions that others have pointed out.

提交回复
热议问题