递归算法之Fibonacci 斐波那契数列第n个数的求解

  Fibonacci 斐波那契数列第n个数的求解,也可以用递归和非递归的形式实现,具体如下,dart语言实现。

 1 int fibonacci(int n) {
 2   if (n <= 0) throw StateError('n cannot be <= 0!');
 3   return n > 2 ? fibonacci(n - 1) + fibonacci(n - 2) : 1;
 4 }
 5 
 6 int fibonacciNonrecursive(int n) {
 7   if (n <= 0) throw StateError('n cannot be <= 0!');
 8   if (n < 3) return 1;
 9   int a = 1, b = 1;
10   while (n-- > 2) {
11     b += a;
12     a = b - a;
13   }
14   return b;
15 }

 

posted on 2019-05-07 18:07  Burkut  阅读(1204)  评论(0编辑  收藏  举报