2
votes

I'm trying to use a recursive function Power in Racket that takes as input two numbers x and y and returns xy, where x and y can be positive or negative.

;a power b
(printf "Enter value of X: ")
(define a (read))
(printf "Enter value of n: ")
(define b(read))
(define (power a b) (if (= b 0) 1 (* a (power a (- b 1 )))))
(define (DisplayResult a messg b mess res) (display a) (display messg)(display b) (display mess) (display res))
(DisplayResult a " power " b " is " (power a b))

How can the program accept negative power?

1

1 Answers

2
votes

We can use this rule:

a^-b = 1 / a^b

or if we insert -b as b:

a^b = 1 / a^-b

Your power handles the case where b is positive, so we can reuse it to define an extended-power that handles the negative case:

(define (extended-power a b)
  (if (negative? b)
      (/ 1 (power a (- b)))
      (power a b)))