Chinaunix首页 | 论坛 | 博客
  • 博客访问: 328133
  • 博文数量: 79
  • 博客积分: 2466
  • 博客等级: 大尉
  • 技术积分: 880
  • 用 户 组: 普通用户
  • 注册时间: 2006-02-07 16:47
文章分类

全部博文(79)

文章存档

2014年(3)

2012年(7)

2011年(14)

2010年(2)

2009年(2)

2008年(2)

2007年(18)

2006年(31)

分类: Python/Ruby

2014-08-30 20:52:38

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.


点击(此处)折叠或打开

  1. def frec(n) {
  2.     if (n<3) return n;
  3.     return 3*frec(n-1) + 2*frec(n-2) + frec(n-3);
  4. }

  5. def fite(n) {
  6.     def fite_impl;
  7.     fite_impl = { m, t, arr ->
  8.         if (m == t) return arr[2];
  9.         if (m > t) return arr[t];
  10.         return fite_impl(m+1, t,
  11.             [arr[1], arr[2], arr[0] + 2*arr[1] + 3*arr[2]]);
  12.     }
  13.     fite_impl(2, n, [0, 1, 2]);
  14. }

  15. println "${frec(4)}, ${fite(4)}"
  16. println "${frec(3)}, ${fite(3)}"
  17. println "${frec(2)}, ${fite(2)}"
  18. println "${frec(1)}, ${fite(1)}"
  19. println "${frec(0)}, ${fite(0)}"

阅读(368) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~