Hey guys. Im new to these forums and was hoping i could get some help. Trying to figure out how to divide a number by another number in scheme without using /. I have written these functions that i can use in creating the divide function:

(define pwr
  (lambda (a b) 
     (= b 0)
     (* a(pwr a(- b 1))))))

(define (add c d)
   (= d 0)
   (add (+ c 1) (- d 1))))

(define (subt e f)
   (= f 0)
   (subt (- e 1) (- f 1))))

(define (multi g h)
   (= h 0)
   (add g(multi g(- h 1)))))

It is supposed to be done like how the multi function above was done. (by using add in this case). I am thinking there is some way to do it by using multi, but i cant figure it out : /

Any help appreciated!
ty :)

7 Years
Discussion Span
Last Post by tuffff

From my first days with scheme… it’s not pretty but it works. Please ignore the markup, “divide-2” is just a function name and “d” just a variable.

; divides two numbers until cutoff is reached
(define (divide n d cutoff)
  (let ((step 10)) ; any value >1 will work
    (define (loop i p sum)
      (letrec ((sp (expt step p))
               (dp (* d sp))
               (q (quotient i dp))
               (r (remainder i dp))
               (new-sum (+ sum (* q sp))))
          ((= r 0)
          ((< (abs r) cutoff)
           (exact->inexact new-sum))
            (loop r (- p 1) new-sum)))))
    (loop n 0 0)))

; divides two numbers until cutoff is reached -- without quotient/remainder
(define (divide-2 n d cutoff)
  (let ((step 10)) ; any value >1 will work
    (define (loop i ud p sum)
        ((= i 0)
        ((< (abs i) cutoff)
         (exact->inexact sum))
          (letrec ((sp (expt step p))
                   (dp (* ud sp))
                   (new-sum (+ sum sp)))
                ((< dp i)
                 (loop (- i dp) ud p new-sum))
                  (loop i ud (- p 1) sum)))))))
    (if (< n 0)
      (if (< d 0)
        (loop (- 0 n) (- 0 d) 0 0)
        (- 0 (loop (- 0 n) d 0 0)))
      (if (< d 0)
        (- 0 (loop n (- 0 d) 0 0))
        (loop n d 0 0)))))

Thanks! :D did not even occur to me to do it like that :P .... i came up with:

(define (divide x y)
    (< x y)
    (+ 1(divide (- x y) y))))

You should have said that you only want integer division :)

But for that task, you solution is much cleaner, but not tail-recursive :S

Edited by tuffff: n/a

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.