Exercise 1.11. A function f is defined by the rule that f(n) = n if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n -
3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a procedure that
computes f by means of an iterative process.
-
def frec(n) {
-
if (n<3) return n;
-
return 3*frec(n-1) + 2*frec(n-2) + frec(n-3);
-
}
-
-
def fite(n) {
-
def fite_impl;
-
fite_impl = { m, t, arr ->
-
if (m == t) return arr[2];
-
if (m > t) return arr[t];
-
return fite_impl(m+1, t,
-
[arr[1], arr[2], arr[0] + 2*arr[1] + 3*arr[2]]);
-
}
-
fite_impl(2, n, [0, 1, 2]);
-
}
-
-
println "${frec(4)}, ${fite(4)}"
-
println "${frec(3)}, ${fite(3)}"
-
println "${frec(2)}, ${fite(2)}"
-
println "${frec(1)}, ${fite(1)}"
-
println "${frec(0)}, ${fite(0)}"
阅读(438) | 评论(0) | 转发(0) |