方案递归完美数字(初学者,希望容易修复) [英] SCHEME recursion perfect number (beginner, hopefully easy fix)

查看:164
本文介绍了方案递归完美数字(初学者,希望容易修复)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有我的完美数字功能的问题。代码的目的是确定数字是否是一个完美的数字,意味着它等于除数的总和。例如:6。我的代码有问题。这里是我的函数:

$ $ 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 如果表达式必须在两个定义之外帮助程序,目前是里面 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)))
pre>

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆