How to do exponentiation in clojure?

2019-03-08 12:16发布

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

13条回答
Animai°情兽
2楼-- · 2019-03-08 12:45

You can use java's Math.pow or BigInteger.pow methods:

(Math/pow base exponent)

(.pow (bigint base) exponent)
查看更多
Ridiculous、
3楼-- · 2019-03-08 12:52

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)))
查看更多
Bombasti
4楼-- · 2019-03-08 12:53

A simple one-liner using reduce

(defn pow [a b] (reduce * 1 (repeat b a)))
查看更多
孤傲高冷的网名
5楼-- · 2019-03-08 12:59
user=> (.pow (BigInteger. "2") 10)
1024
user=> (.pow (BigInteger. "2") 100)
1267650600228229401496703205376
查看更多
Explosion°爆炸
6楼-- · 2019-03-08 13:01

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)
查看更多
何必那么认真
7楼-- · 2019-03-08 13:02

Clojure has a power function that works well: I'd recommend using this rather than going via Java interop since it handles all the Clojure arbitrary-precision number types correctly.

It's called expt for exponentiation rather than power or pow which maybe explains why it's a bit hard to find..... anyway here's a small example:

(use 'clojure.math.numeric-tower)  ; as of Clojure 1.3
;; (use 'clojure.contrib.math)     ; before Clojure 1.3

(expt 2 200)
=> 1606938044258990275541962092341162602522202993782792835301376
查看更多
登录 后发表回答