Skip to content

Commit f7494bc

Browse files
committed
Merge pull request ruanyf#209 from NumerHero/gh-pages
增加fibonacci 尾递归算法
2 parents d67e8eb + 1e1ea90 commit f7494bc

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

docs/function.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1209,6 +1209,37 @@ function factorial(n, total) {
12091209
factorial(5, 1) // 120
12101210
```
12111211

1212+
还有一个比较著名的例子,就是计算fibonacci 数列,也能充分说明尾递归优化的重要性
1213+
1214+
如果是非尾递归的fibonacci 递归方法
1215+
1216+
```javascript
1217+
function Fibonacci (n) {
1218+
if ( n <= 1 ) {return 1};
1219+
1220+
return Fibonacci(n - 1) + Fibonacci(n - 2);
1221+
}
1222+
1223+
Fibonacci(10); // 89
1224+
// Fibonacci(100)
1225+
// Fibonacci(500)
1226+
// 堆栈溢出了
1227+
```
1228+
1229+
如果我们使用尾递归优化过的fibonacci 递归算法
1230+
1231+
```javascript
1232+
function Fibonacci2 (n , ac1 = 1 , ac2 = 1) {
1233+
if( n <= 1 ) {return ac1};
1234+
1235+
return Fibonacci2 (n-1 , ac2 , ac1 + ac2);
1236+
}
1237+
1238+
Fibonacci2(100) // 354224848179262000000
1239+
Fibonacci2(1000) // 4.346655768693743e+208
1240+
Fibonacci2(10000) // Infinity
1241+
```
1242+
12121243
由此可见,“尾调用优化”对递归操作意义重大,所以一些函数式编程语言将其写入了语言规格。ES6也是如此,第一次明确规定,所有ECMAScript的实现,都必须部署“尾调用优化”。这就是说,在ES6中,只要使用尾递归,就不会发生栈溢出,相对节省内存。
12131244

12141245
### 递归函数的改写

0 commit comments

Comments
 (0)