HomeComputer programmingScheme: Exponents

Scheme: Exponents

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)

RELATED ARTICLES

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments

Cleveland Furia on How to Clear Google Activity
Sid Wohlfarth on How to Clear Google Activity
Riley Magsayo on How to Clear Google Activity
สมัครรับเครดิตฟรี ทันที on How to improve Remote Desktop Protocol Performance
Neal Wangstad on How to Clear Google Activity
Slavcho Andov on How to install Ubuntu
Slavcho Andov on How to fix bad sectors
Sheraz Ali on How to Backup Android