Rene Ferguson
Rene Ferguson

Reputation: 39

Recursive Multiplication in Scheme (trouble with negatives)

I am trying to multiply in Scheme using recursion, and I am able to do so with positive numbers but not negatives (they get stuck in an infinite loop). I assume the problem comes in the 3rd and 4th lines, which I wrote in an attempt to be able to handle negatives. Any help would be appreciated :)

(define Multiply(lambda (x y)
                      (if (eq? x 0) 0 (if (eq? y 0) 0 ;if either x or y are zero, return 0
                         (if (> 0 x) (- 0 (+ x (Multiply x (- y 1)))) 
                             (if (> 0 y) (- 0 (+ x (Multiply x (- y 1))))
                                 (+ x (Multiply x (- y 1)))))))))

Upvotes: 0

Views: 991

Answers (1)

assefamaru
assefamaru

Reputation: 2789

Since multiplication is associative, you can have

x * (-1 * y)  =  (x * -1) * y

With this in mind, you can convert y to positive whenever it is less than zero, by multiplying both x and y with -1. Consider the following:

(define (multiply x y)
  (cond
    ((zero? x) 0)
    ((zero? y) 0)
    ((< y 0)
     (multiply (- x) (- y)))
    (else
     (+ x (multiply x (sub1 y))))))

Upvotes: 1

Related Questions