我的完美数函数有问题。代码的目标是确定该数字是否是完美数字,即它是否等于其除数之和。例如:6。我的代码有问题。这是我的功能:
(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)))))))
最佳答案
你差点就明白了!不过,也存在一些问题。首先,您在 sum-proper-divisors
中遗漏了一个案例:您询问 y
是否为 1,以及 if (divides y x)
,但是如果 y
不能整除 x
会发生什么?
第二个问题是最后一个 if
表达式必须在两个帮助程序的定义之外,目前它在 sum-proper-divisors 内部
。正确缩进代码将更容易发现此类错误。
这就是正确的解决方案,因为这看起来像家庭作业,我会让你填空:
(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)))
关于formatting - SCHEME 递归完美数(初学者,希望很容易修复),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12379432/