检查立方体和等于和猜想平方的Scheme程序
我试图编写一个迭代过程,如果立方体和等于和的平方为真,则返回#t,否则#f,当第一个整数时,可能分别写下“和的平方”和“立方体和”函数可以帮助您更好地了解如何组合它们 假设我们想将总和从1平方到n,即:检查立方体和等于和猜想平方的Scheme程序,scheme,Scheme,我试图编写一个迭代过程,如果立方体和等于和的平方为真,则返回#t,否则#f,当第一个整数时,可能分别写下“和的平方”和“立方体和”函数可以帮助您更好地了解如何组合它们 假设我们想将总和从1平方到n,即:(1+2+…+n)²。我们可以编写如下函数: (define (square-of-sum a b acc) (if (> a b) (sqr acc) ;; square the sum upon ret
(1+2+…+n)²
。我们可以编写如下函数:
(define (square-of-sum a b acc)
(if (> a b)
(sqr acc) ;; square the sum upon return
(square-of-sum (add1 a) b (+ acc a))))
(define (combined a b cubed-acc sum-acc )
(if (> a b)
(= cubed-acc (sqr sum-acc))
(combined (add1 a) b (+ cubed-acc (expt a 3)) (+ sum-acc a))))
类似地,将1到n的立方值相加,即:1³+2³+…+n³
,我们可以写:
(define (sum-of-cubed a b acc)
(if (> a b)
acc
(sum-of-cubed (add1 a) b (+ acc (expt a 3)))))
因此,将它们组合到您想要的效果将如下所示:
(define (square-of-sum a b acc)
(if (> a b)
(sqr acc) ;; square the sum upon return
(square-of-sum (add1 a) b (+ acc a))))
(define (combined a b cubed-acc sum-acc )
(if (> a b)
(= cubed-acc (sqr sum-acc))
(combined (add1 a) b (+ cubed-acc (expt a 3)) (+ sum-acc a))))
上面的组合
函数对应于您的iter
,推测
可以重新编写为:
(define (conjecture n)
(define (iter count cube-sum sum)
(cond
((> count n)
(= cube-sum (sqr sum)))
(else
(iter (add1 count)
(+ cube-sum (expt count 3))
(+ sum count)))))
(iter 1 0 0))
然后,对于任何自然数n
,您将有:
(conjecture n)
=> #t
. :)