formatting - SCHEME 递归完美数(初学者,希望很容易修复)

标签 formatting scheme racket perfect-numbers

我的完美数函数有问题。代码的目标是确定该数字是否是完美数字,即它是否等于其除数之和。例如: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/

相关文章:

java - 无需大量开销即可获得格式良好的时间戳?

python - 如何在python中将相似文件名的文件组合在一起?

functional-programming - 方案模式检查它是否是一个数字

racket - DrRacket 组合列表

recursion - 方案反转列表

java - CSS - 圆形边框看起来像两个重叠的按钮

Excel:如果在另一列中发现重复的单元格值,则突出显示绿色

linux - 从命令行运行 Scheme

scheme - 提前退出递归过程

c - Guile 程序错误 "procedure->pointer": Wrong Type Argument in Position 1