遞歸算法之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