我正在尝试在Racket上实现前n个奇数平方和的递归过程 (从1开始) 例如,(sum-alt-squares-recursive 0)为0 (sum-alt-squares-recursive 1)是1(1 ^ 2) (sum-alt-squares-recursive 2)是10(3 ^ 2 + 1 ^ 2) (sum-alt-squares-recursive 3)是35(5 ^ 2 + 3 ^ 2 + 1 ^ 2)
答案 0 :(得分:0)
这是一个使用线性迭代过程的递归过程
(define (sum-alt-squares-recursive x (y 1) (z 0))
(if (zero? x)
z ; if x is zero, return accumulator z
(sum-alt-squares-recursive (- x 1) ; x goes down by 1 each iteration
(+ y 2) ; y starts at 1 and goes up by 2 each iteration
(+ z (* y y)) ; z, goes up by y^2 each time
)))
(sum-alt-squares-recursive 1) ; => 1
(sum-alt-squares-recursive 2) ; => 10
(sum-alt-squares-recursive 3) ; => 35