【问题标题】:SCHEME recursion perfect number (beginner, hopefully easy fix)SCHEME 递归完美数(初学者,希望容易修复)
【发布时间】:2022-05-02 18:54:29
【问题描述】:

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

【问题讨论】:

  • 如果您已经知道它“可能是括号问题”,那么您应该能够自己修复它。
  • Racket 要求我保留尾括号

标签: formatting scheme racket perfect-numbers


【解决方案1】:

你几乎明白了!但是,有几个问题。首先,您在sum-proper-divisors 中遗漏了一个案例:您询问y 是否为一以及(divides y x) 是否为一,但是如果y 不除x 会发生什么?

第二个问题,最后一个if 表达式必须在两个辅助过程的定义之外,目前它在inside 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)))

【讨论】:

  • 它在 x=0 处进入无限循环,也许删除 if 并将 ((= y 1) 1) 更改为 ((&lt;= y 0) 0) ?
  • 我很抱歉,但我似乎在我的建议中引入了一个错误,我没有注意到 0 会像这样“变成”一个完美的数字。 if 谓词应该是 &lt;= x 1 。条件不是问题。非常抱歉。
【解决方案2】:
(define (is-perfect x)

  (define (divides a b) (= (modulo b a) 0))

  (define (sum-proper-divisors y)
    (if (< y 1)  
       0                                     ; stop recursion here
       (if (divides y x)
         (+ y (sum-proper-divisors (- y 1))) ; add 'y' to the sum
         (sum-proper-divisors (- y 1))       ; else continue testing and sum divisors below 'y'
       )
    )
  )

  ; now, use the defined functions to obtain and return result
  (if
    (<= x 0)
      #f      ;; by definition, perfect number must be a positive integer, so...
      (= (sum-proper-divisors (- x 1)) x) ; ...else.
  )
  
)

测试 0-999:

(for ([i 1000])
   (cond 
     ((is-perfect i)
        (printf "~a IS PERFECT~n" i)
     )
   )
)

输出:

6 IS PERFECT
28 IS PERFECT
496 IS PERFECT
> 

【讨论】:

    猜你喜欢
    • 2011-07-12
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 2021-05-03
    • 2016-01-31
    相关资源
    最近更新 更多