SCHEME recursion perfect number (beginner, hopeful

2019-07-07 16:27发布

问题:

having an issue with my perfect number function. The objective of the code is to determine if the number is a perfect number, meaning it is equal to the sum of its divisors. Ex:6. Im having trouble with my code. Here's my function:

(define (is-perfect x)
  (define (divides a b) (= (modulo b a) 0))
  (define (sum-proper-divisors y)
    (if (= y 1)
        1
        (if (divides y x)
            (+ y (sum-proper-divisors (- y 1)))
        (if (= x 1)
            #f
            (= (sum-proper-divisors (- x 1)
                                    x)))))))

回答1:

You almost got it! there are a couple of problems, though. First, you're missing a case in sum-proper-divisors: you ask if y is one and if (divides y x), but what happens if y does not divide x?

The second problem, is that the last if expression must be outside of the definition of the two helper procedures, currently it's inside sum-proper-divisors. Properly indenting your code will make easier to find this kind of errors.

This is how a correct solution looks, because this looks like homework I'll let you fill-in the blanks:

(define (is-perfect x)
  (define (divides a b)
    (= (modulo b a) 0))
  (define (sum-proper-divisors y)
    (cond ((<= y 1)
           1)
          ((divides y x)
           (+ y (sum-proper-divisors (- y 1))))
          (else
           <???>))) ; what goes in here?
  (if (= x 1)
      #f
      (= (sum-proper-divisors (- x 1)) x)))