方案递归完美数字(初学者,希望容易修复) [英] SCHEME recursion perfect number (beginner, hopefully easy fix)
问题描述
$ $ p $
(define(is-perfect x)
(define(divide ab)(=(modulo ba)0))
(define(sum-proper-divisors y)
(if(= y 1)
1
(if(divs yx)
+ y(sum-proper-divisors(-y 1)))
(if(= x 1)
#f
(=(sum-proper-divisors( - x 1)
x)))))))
差不多了!但是有一些问题。首先,你在 这是一个正确的解决方案,因为这看起来像作业,我会让你填写空格: sum-proper-divisors
中缺少一个例子:你问如果 y
是1,如果(除yx)
,但是如果 y
不会将 x $ c $第二个问题是,最后一个
pre> 如果
表达式必须在两个定义之外帮助程序,目前是里面 sum-proper-divisors
。正确地缩进你的代码会使找到这种错误更容易。
$ $ p $ $ $ $ $ $ $ $ $ $ $ $ $ =(modulo ba)0))
(define(sum-proper-divisors y)
(cond((<= y 1)
1)
)
(+ y(sum-proper-divisors(-y 1))))
(else
< ???>)));这里是什么?
(如果(= x 1)
#f
(=(sum-proper-divisors( - x 1))x)))
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)))))))
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)))
这篇关于方案递归完美数字(初学者,希望容易修复)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!