递归算法之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 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM