Scheme – exponents

Contributor Icon Contributed by William_Wilson  
Tag Icon Tagged: 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 bas b and the exponent n, the code detemines if the exponent is 0 in which case it returns 1. Otherwise, it determines if n is even and can be divided by 2 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: william_a_wilson@hotmail.com
-William. ยง (marvin_gohan)

 

1 Comment -


  1. Alvaro Hultman said on September 8, 2011

    Is it possible to install multiple joomla site on one wamp server?

 

RSS feed for comments on this post. TrackBack URL

Leave a comment -