SCHEME recursion perfect number (beginner, hopefully easy fix)

北城余情 提交于 2019-12-11 01:49:04

问题


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)))


来源:https://stackoverflow.com/questions/12379432/scheme-recursion-perfect-number-beginner-hopefully-easy-fix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!