Scheme: Exponents

Posted October 14, 2006 by William_Wilson in Computer programming

This Scheme code example shows how to implement exponents by raising a given base by a given exponent through succesive squaring.

Given the base b and the exponent n, the code determines if the exponent is zero, in which case it returns one. Otherwise, it determines if n is even and can be divided by two or if an odd adaptation needs to be performed first.

(define (exp b n)
(cond ((= n 0) 1) ;0 base case
((= n 1) b) ;1 base case
((even? n) (exp (square b) (/ n 2))) ;even case using (b^2)^n/2
(else (* b (exp b (+ n -1))))) ;odd case using b*b^n-1

Questions/Comments: [email protected]
-William. ยง (marvin_gohan)

The Conversation

Follow the reactions below and share your own thoughts.