Sunday, 31 March 2019

Exponent (LISP - Scheme)

Exponent - Lisp



In this post we will discuss how to make a normal program using which we can calculate exponent of the given numbers. i.e. 2^3 or 52^40 etc. I mean google it and you won't get a precise answer for 52^40 but using lisp you can get a more accurate answer. So lets get started...


So basic approach to calculate b^n is multiply b n times. So if you have followed my previous posts you might know how to proceed further as its very similar to the methods we used earlier to solve the problems. 


So the function for exponent is like : 



Firstly we will start by defining the function which will take in 2 arguments b & n.

(define (expo b n)

After that we want to multiply b n times and till n becomes 0 and when that happens we will then return 1 i.e. b^0 = 1. So the code will do something like b*(b^(n-1)) till n-1 = = 0.

So in further code its like this :

(cond ((= n 0) 1)
           (else (* b (expo b (- n 1))))))

Written By,
Sarvesh Bhatnagar