schemeracketcountingfactorsfactorization

How to calculate the number of divisors in a list for a number in scheme


How to I create a function called numDivisors. The function is defined as (numDivisors n listOfNums) and it counts the number of integers in the list that divide n without any remainder.

Example of the function call (numDivisors 10 '(1 20 30 2 5 40 10 60)) returns 4 from (1 2 5 10)

Current code:

(define numDivisors
  (lambda (x lst)
    (cond
      ((null? lst) 0)
      ((eq? (remainder 10 (car lst)) 0) (+ 1 (numDivisors x (cdr lst))))
      )
    )
  ) 

Solution

  • Your solution is close.

    First you need to change eq? to =, which tests equality of numbers, and change (remainder 10 ...) to (remainder x ...), so that 10 is no longer hard-wired into your solution.

    Second, you need to add a third clause to your cond to handle the case where the remainder is not 0. I'll let you think about that; given what you have done so far, I am confident you will figure it out.

    And you should stack those three closing parentheses at the end of the last line of code instead of placing them on lines by themselves.

    An experienced Scheme programmer would probably write:

    (define (numDivisors n xs)
      (define (divides? d n) (zero? (modulo n d)))
      (length (filter (lambda (d) (divides? d n)) xs)))
    

    If that makes no sense at all, you should probably wait a few weeks. I'm sure your instructor will soon have you writing code like that.