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 }

 

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄