Finding Amount of Divisors

301 Views Asked by At

I need to write a function in #lang racket that determines the amount of divisors a positive integer has. (Ex: 6 has 4 divisors; 1,2,3,6)

So far I have:

(define (divides a b) (if (= 0 (modulo a b)) #t #f))

I need to use this helper function to write the function (divisors-upto n k) that that computes the number of divisors n has between 1 and k (so it computes the number of divisors of n up to the value k).

1

There are 1 best solutions below

0
On

This is easiest done1 with a for loop, in particular for/fold, given that you already have your divides function.

(define (divisors num)
  (for/fold ([acc 0]
             [n (in-range num)])
    (if (divides n num) <acc+1> <acc>)))

Basically, you are looping over the list, and keeping an accumulator, and whenever a number is dividable, increment your accumulator. See if you can fill in the expressions for <acc+1> and <acc> in the code above.

1You could also do this with list length and filter. See if you can figure out how.