How to do exponentiation in clojure?

前端 未结 13 1820
执笔经年
执笔经年 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:56

    SICP inspired full iterative fast version of 'sneaky' implementation above.

    (defn fast-expt-iter [b n]
      (let [inner (fn [a b n]
                    (cond
                      (= n 0) a
                      (even? n) (recur a (* b b) (/ n 2))
                      :else (recur (* a b) b (- n 1))))
            ]
        (inner 1 b n)))
    

提交回复
热议问题