码迷,mamicode.com
首页 > 编程语言 > 详细

用JavaScript实现斐波拉契数列

时间:2015-08-19 19:53:04      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

<html>
    <head>
        <meta charset="utf-8" />
        <title>html</title>
        <script type="text/javascript">
            function getNthFibonacci(num){
            if(num < 2){
                return num;
            }
            var first = 0;
            var second = 1;
            var third;
            for(var i = 2;i < num;i ++){
                third = first + second;
                first = second;
                second = third;
            }
            return third;
        }
        function output(){
            var number = 10;
            var answer = getNthFibonacci(number);
            document.write(answer);
        }
        </script>
    </head>

    <body>
    </body>
    <script type="text/javascript">output()</script>
</html>

建议不适用递归调用,当数字很大时,递归会非常耗时。

用JavaScript实现斐波拉契数列

标签:

原文地址:http://www.cnblogs.com/Decmber/p/4743123.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!