0

I'm trying to create a Division function using only subtraction. What I have so far is enough to handle positive numbers. What keeps tricking me up is handling it for negative numbers. I can go ahead and just grab the absolute value of x and y and it works perfectly, but then my answer can never be negative. Anyone here whose had to do something similar before?

(define Divide (lambda (a b c)
                    (if (> a 0)
                        (Divide (- a b) b (+ c 1))
                        c
                        )
                    )
  )
Devyn Hedin
  • 37
  • 3
  • 7

2 Answers2

1

In cases like this you often want to define an auxiliary function that the main function calls after massaging the data:

(define (Divide a b)
  (define (go a b c)
    (if (> a 0)
      (go (- a b) b (+ c 1))
      c))
  (cond
    [(and (> a 0) (> b 0))
     (go a b 0)]
    [(and (< a 0) (< b 0))
     (go (- a) (- b) 0)]
    [(< a 0)
     (- (go (- a) b 0))]
    [(< b 0)
     (- (go a (- b) 0))]))
Brendan Cannell
  • 679
  • 4
  • 11
1

You can assign the product of sign values of a and b to a variable, then deal with only absolute values of both a and b while doing the recursion. Output then becomes the product of c and the sign variable as (* c sign). Consider the following:

(define (divide num denom)
  (let div ([n num]
            [d denom]
            [acc 0]
            [sign 1])
    (cond
      [(< n 0)
       (div (- n) d acc (- sign))]
      [(< d 0)
       (div n (- d) acc (- sign))]
      [(< n d)
       (* sign acc)]
      [else
       (div (- n d) d (add1 acc) sign)])))

For example,

> (divide 10 7)
1
> (divide -10 7)
-1
> (divide -10 -7)
1
> (divide 10 -7)
-1

Note that if you use the condition (if (> a 0) ... instead of (if (>= a b) ..., then you add an extra step in your recursion, which is why using your function, (Divide 10 7 0) outputs 2.

assefamaru
  • 2,751
  • 2
  • 10
  • 14