In: Computer Science
Write a LISP function POWER that takes a list containing exactly two numeric atoms and computes the first atom raised to the power of the second atom. For example:
(POWER ‘(2 4)
Returns the value 16
In this problem, a list containing exactly two numeric atoms is passed as an argument and the return value is the first atom raised to the power of the second atom.
Following is the recursive method to solve this problem. Suppose we are given a list (m n) and we need need to calculate mn . First, check if n is equal to zero or not. If yes, return 1. Else, do the same process for mn-1 and return m*mn-1. Following is the LISP program for this:
;POWER function to calculate base to the power exponent
;takes a list (m n) as an argument
(defun POWER(list-num)
(setq m (nth 0 list-num)) ; m stores the first element of the
list
(setq n (nth 1 list-num)) ; n stores the second element of the
list
(setq z (- n 1)) ; z stores the value of n-1
(if (= n 0) 1 ; if n is zero, return 1
(* m (POWER (list m z))))) ; else recursive call with argument (m
n-1) and multiply with m
(write(POWER '(2 4))) ; call the POWER function
And following is the output when the list is (2 4):