testing - 方案平方和检验

标签 testing scheme sum

我编写了一个平方和函数来测试数字 n 是否可以写成两个平方和。我的代码如下:

(define (square x) (* x x))
(define (sum-of-squares n)
 (define (sum-of-squares-h k)
    (cond ((= k n) #f)
       ((= n (+ (square(floor(sqrt k)))(square(floor(sqrt(- n k))))))#t)
                (sum-of-squares-h (+ k 1))))
    (sum-of-squares-h 1))    

当我测试诸如:

(sum-of-squares 1)
(sum-of-squares 2)
(sum-of-squares 4)
(sum-of-squares 8)
(sum-of-squares 10)

我的输出是:

#f
#t
2
2
#t

我哪里出错了/我该怎么做才能解决这个问题?我已经看到了解决这个问题的其他方法,但是如果有人可以通过使用我已有的东西来帮助我,那就太好了。我对 floor 函数不太熟悉,所以我可能使用不正确。

编辑 - 稍作调整的代码

 (define (square x) (* x x))
  (define (sum-of-squares n)
   (define (sum-of-squares-h k)
     (cond ((= k n) #f)
           ((< n 4) #f)
           ((= n (+ (square(floor(sqrt k)))(square(floor(sqrt(- n k))))))#t)
                 (sum-of-squares-h (+ k 1))))
     (sum-of-squares-h 1))     

最佳答案

你忘记了最后一个条件中的 else 部分:

(define (sum-of-squares n)
  (define (sum-of-squares-h k)
    (cond ((= k n)
           #f)
          ((= n (+ (square (floor (sqrt k)))
                   (square (floor (sqrt (- n k))))))
           #t)
          (else
           (sum-of-squares-h (+ k 1)))))
  (sum-of-squares-h 1))

关于testing - 方案平方和检验,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19054052/

相关文章:

javascript - 我应该对我的/src 文件还是/build 文件进行单元测试?

testing - Windows 7 上的经典 ASP Web 服务器

macros - 如何在 Scheme 中的列表中映射宏?

Mysql 仅将一行求和一次 - 使用 Group By

MySQL 对许多使用 CASE WHEN 的 SUM() 进行平均——有更好的方法吗?

testing - Angular e2e 测试 - 未捕获的 ReferenceError : inject is not defined

java - android 中 ProgressDialog 的 Robolectric 测试

functional-programming - 方案中的 eq?、eqv?、equal? 和 = 有什么区别?

scheme - gimp 脚本-fu : drawing a simple line

sql - ORA-00934 : group function is not allowed here 00934. 00000 - "group function is not allowed here"