Tuesday, 22 January 2019

Reverse of a number - LISP(SCHEME)

Reverse of a number - LISP(Scheme)


Reverse of a given number involves 2 main task , 
  1. Finding what the last digit is
  2. Finding the remains number aside from last digit
If we solve these tasks then we can easily find the reverse of a given number by simply recursively finding the last digit and trimming the original number. 

Aside from this , there is one other problem which we might face which is : the problem of storing the last digit obtained... We can solve that by the following method:
  1. Intitalize a variable temp which will hold the reversed number with 0.
  2. perform temp = (temp * 10 ) + last digit.
we initialise temp = 0 only once whereas 2nd step is done at every step, in second step we are actually creating a space for last digit by multiplying it with 10, after which we can simply add the last digit to it.


Now the code for finding out reverse of a given number can be written as :




Now, we basically solve the first problem of finding last digit by using modulo operator...
i.e (modulo number 10) , we solve the second problem by finding the quotient of the number, So our code turns out as keep finding the reverse until the original number becomes 0 , and when that happens return the reversed number.


Written By,
Sarvesh Bhatnagar


Friday, 11 January 2019

Factorial - LISP(Scheme)

A Program for finding factorial using Scheme


Factorials n or n! is defined as product of all positive integers upto n.  Simply n! 
for example : 

5! = 5 * 4 * 3 * 2 * 1

Now there are two ways to calculate factorials, one is if we go in a backward direction i.e  in a decremental manner in which we recursively multiply the factorial(n-1) with n or we can go in an incremental manner in which we start from one and progress towards n i.e. 1 * 2 * 3 * ... * n-1 * n.
Aside from that , another condition which we need to know is 0! = 1.

In this post we will look how to implement the same in scheme.

When going in backward direction our scheme code will look like :

(define (fact n)(cond ((= n 1) 1)
                                   ((= n 0) 1)
                                   (else (* n (fact (- n 1))))))

In the above code we simply handle the possible edge cases first and continue until we reach the edge case. i.e. n == 1 or n == 0

Similarly we can define for an incremental iterative approach as : 

(define (fact n t)(cond((> n 0) (fact (- n 1) (* t n)))
                                     ( else t)))

Benefit of the incremental iterative approach is that if we know the state values, we can start directly from that particular state for example :
2nd state of 5! is :  t = 5 , n = 4
3rd state of 5! is :   t = 20 , n = 3
and so on...

Written By,
Sarvesh Bhatnagar