Recursive Multiplication in Scheme (trouble with negatives)

丶灬走出姿态 提交于 2019-12-13 03:35:31

问题


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)))))))))

回答1:


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))))))


来源:https://stackoverflow.com/questions/49910863/recursive-multiplication-in-scheme-trouble-with-negatives

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!