0

我正在编写一个函数来计算一个数字的除数。例如 4 将有 3 个除数。我写了一个辅助函数如下:

(define (divisors-upto n k)
  (cond((= k 0) 0)
      ((= n 0) 0)
      ((= k 1) 1)
      ((divides k n) (+ 1 (divisors-upto n (- k 1))))
      (else (divisors-upto n (- k 1)))))

但在我的下一个函数中,我无法正确使用我的辅助函数。以下函数是否适用于计算除数?

(define ( divisors n ) ( divisors-upto n n ))
4

1 回答 1

1

The procedure looks good in principle. As long as the procedure divides is correctly implemented, it should work without problems. For example:

(divisors 10)
=> 4 ; 10, 5, 2 and 1 are divisors of 10

FYI, when you have a helper procedure that gets called with one or more extra parameters from the "main" procedure, and the helper procedure is never going to be used elsewhere, it's a good idea to declare the helper as an inner definition, for example:

(define (divisors n)
  (define (divisors-upto n k)
    (cond ((= k 0) 0)
          ((= n 0) 0)
          ((= k 1) 1)
          ((divides k n) (+ 1 (divisors-upto n (- k 1))))
          (else (divisors-upto n (- k 1)))))
  (divisors-upto n n))
于 2013-09-05T18:49:48.583 回答