Reputation:
Hey so I am creating a function (divides n), which is supposed to calculate the number of divisors in a number n with the help of a modulo function and a function that acts as a counter going down from the number n. My issue is that the modulo function should output a true or false depending on whether the number is whole however my if statement
(if (= (divides n k) #f)
0
Im not sure why but the code wont evaluate the if statement as true or false.. it just skips it. Also im not sure that 0 should be the correct output I want it to just skip that number and not count it.
Heres my code:
(define (divides a b) (= 0 (modulo b a)))
(define (divisors-upto n k)
(if (= (divides n k) #f)
0
(+ k (divisors-upto n (- k 1)))))
(define (divisors n) (divisors-upto n n))
(divisors 4) ;for example should produce the result 3
Upvotes: 1
Views: 1239
Reputation: 236004
Start by fixing the divides
procedure, you reversed the arguments to modulo
. This is how it should look:
(define (divides a b)
(= 0 (modulo a b)))
The above tests if b
divides a
, that's how you're using it in the divisors-upto
procedure. Also you should replace this:
(= (divides n k) #f)
With this:
(equal? (divides n k) #f)
Or even better, this:
(not (divides n k))
Apart from that, isn't this the same question that you posted before? I told you there that you're missing a case in the recursion, look at my previous answer in the link.
If it's not the same procedure, then I'm not really sure of what you want to do: in this question you state that the procedure "is supposed to calculate the number of divisors in a number", but that's not what the procedure is doing - you're adding the actual divisors (the k
parameter in the procedure) and not the number of divisors. And again, you'd be missing a case - what happens if the current k
is not a divisor? the recursion would exit prematurely! Try to work on this a bit, fill-in the blanks:
(define (divisors-upto n k)
(cond ((zero? k)
<???>) ; how many divisors are there if k is zero?
((not (divides n k))
<???>) ; if k is not a divisor of n, we must proceed without incrementing
(else ; if k is a divisor of n, by how many should the count be incremented?
(+ <???> (divisors-upto n (- k 1))))))
Upvotes: 2