Fibonacci Sequences in JavaScript with/without recursive
来源:互联网 发布:足球教案制作软件 编辑:程序博客网 时间:2024/05/22 17:43
第一种、第二种是一样的方法,就是递归:(可优化,应该将每一个元素的值缓存起来,而不是每次递归都计算一次)
//with Recursion function fibonacci1 (argument) { // body... return (argument <= 1 ? argument : fibonacci1(argument - 1) + fibonacci1(argument - 2)); } window.console.log(fibonacci1(10)); function fibonacci2 (argument) { return (argument <= 1 ? argument : arguments.callee(argument - 1) + arguments.callee(argument - 2)); } window.console.log(fibonacci2(10));
这里可以说一下JS函数实参对象的callee属性。JS函数的实参对象定义了callee和caller属性。在ES5严格模式中,对这两个属性的读写操作都会产生一个类型错误(TypeError)。而在非严格模式下,ES标准规范规定callee属性指代当前正在执行的函数。caller是非标准的,但大多数浏览器都实现了这个属性,它指代调用当前正在执行的函数的函数。通过caller属性可以访问调用栈。callee属性在某些时候会非常有用,比如在匿名函数中通过callee来递归地调用自身。
var factorial = function (x) { if (x == 1) {return 1;} return x * arguments.callee(x-1);};
第三种用的非递归。
//without Recursion function fibo3 (argument) { if(argument <= 1){ return argument; } var fibo = 1; var fiboPre = 1; for (var i = 2; i < argument; ++i) { var temp = fibo; fibo = fibo + fiboPre; fiboPre = temp; } return fibo; } window.console.log(fibo3(10));
第四种也是非递归,但是利用了黄金比率1.618,不过要注意的是这种方法在n>69之后,性能就会下降很快,参考文章看这里:http://www.mathsisfun.com/numbers/fibonacci-sequence.html
//with gold ratio function fibo4 (n) { var sqrt5 = Math.sqrt(5); var alpha = (1+sqrt5)/2; // 黄金比率:1.618... return Math.round(Math.pow(alpha,n) / sqrt5); // Please note that this method holds good till n = 69 only.http://www.mathsisfun.com/numbers/fibonacci-sequence.html } window.console.log(fibo4(3));
0 0
- Fibonacci Sequences in JavaScript with/without recursive
- Recursive Fibonacci
- Recursive Subquery Factoring (Recursive WITH)
- No. 15 - Fibonacci Sequences
- Recursive Lambda in C++
- 【论文笔记】Recursive Recurrent Nets with Attention Modeling for OCR in the Wild
- leetcode- Preorder/Inorder/PostOrder without Recursive
- Distributed transactions in Spring, with and without XA
- Distributed transactions in Spring, with and without XA
- Fast Pixel Operations in .NET (With and Without unsafe)
- potgresql-WITH RECURSIVE与refcursor
- Working-with-files-in-javascript
- Recursive Blocks in Objective-C
- Recursive class initialization in Java
- Recursive Type Signatures in Scala
- [51nod1768]Rikka with Sequences
- PostgreSQL的递归查询(with recursive)
- PostgreSQL的递归查询(with recursive)
- fastsocket优化网络性能原理
- 用Perl处理文本文件时遇到的换行问题
- KMP算法next数组计算方法的优化
- SourceInsight3.5添加库函数支持
- 苹果夜
- Fibonacci Sequences in JavaScript with/without recursive
- 盘点2014年度智慧城市:政策、标准及其它
- 正则表达式
- Linux文本处理工具之sed
- Direct3D 11 拾取
- With as 必须跟select
- Android 开发者不得不面对的六个问题
- 综合错误:Assignment under multiple single edges is not supported for synthesis
- org.apache.http.client.CircularRedirectException: Circular redirect to "http://xxx"问题解决