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)
(if
(= b 0)
1
(* a(pwr a(- b 1))))))

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

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

(define (multi g h)
(if
(= h 0)
0

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

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))))
(cond
((= r 0)
new-sum)
((< (abs r) cutoff)
(exact->inexact new-sum))
(else
(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)
(cond
((= i 0)
sum)
((< (abs i) cutoff)
(exact->inexact sum))
(else
(letrec ((sp (expt step p))
(dp (* ud sp))
(new-sum (+ sum sp)))
(cond
((< dp i)
(loop (- i dp) ud p new-sum))
(else
(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)
(if
(< x y)
0
(+ 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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.