RosettaCodeData/Task/Exponentiation-operator/EchoLisp/exponentiation-operator.ech...

26 lines
732 B
Plaintext

;; this exponentiation function handles integer, rational or float x.
;; n is a positive or negative integer.
(define (** x n) (cond
((zero? n) 1)
((< n 0) (/ (** x (- n)))) ;; x**-n = 1 / x**n
((= n 1) x)
((= n 0) 1)
((odd? n) (* x (** x (1- n)))) ;; x**(2p+1) = x * x**2p
(else (let ((m (** x (/ n 2)))) (* m m))))) ;; x**2p = (x**p) * (x**p)
(** 3 0) → 1
(** 3 4) → 81
(** 3 5) → 243
(** 10 10) → 10000000000
(** 1.3 10) → 13.785849184900007
(** -3 5) → -243
(** 3 -4) → 1/81
(** 3.7 -4) → 0.005335720890574502
(** 2/3 7) → 128/2187
(lib 'bigint)
(** 666 42) →
38540524895511613165266748863173814985473295063157418576769816295283207864908351682948692085553606681763707358759878656