zoukankan      html  css  js  c++  java
  • [转] 兔子数列的递归计算

    斐波那契数列(Fibonacci sequence),又称黄金分割数列
    <!doctype html>
    <html>
     <head>
      <meta charset="UTF-8">
      <title>递归算法示例</title>
      <style type="text/css">
        #result{
            color:red;
            //border:1px solid #000080;
            padding:10px;
        }
        #main{
            margin:10px;
        }
      </style>
      <script src="jquery-1.12.4.min.js"></script>
        <script type="text/javascript">
            $(function(){
                $('#btnCalc').click(function(){
                    var num = parseInt($('#txtCount').val())
                    var strResult = ''
                    for(var i=1;i<=num;i++){
                        var t = new Date()
                        if(i < num){
                            strResult += String(calc(i)) + ' 计算耗时 ' + ((new Date()).getTime() - t.getTime())/1000.0 + ' 秒<br />'    
                        }
                        else{
                            strResult += String(calc(i)) + ' 计算耗时 ' + ((new Date()).getTime() - t.getTime())/1000.0 + ''
                        }
                    }
                    $('#result').html(strResult)
                    $('#result').css('border','1px solid #000080')
                })
    
            })
    
            function calc(num){
                if(num <= 0){
                    return 0
                }
                if(num == 1 || result == 2){
                    return 1
                }
                else {
                    return calc(num-1) + calc(num-2)
                }
            }
    
        </script>
     </head>
     <body>
      <div id="result"></div>
      <div id="main">
        <input type="button" id="btnCalc" value="计算" />
        <input type="text" id="txtCount" value="30" />
      </div>
     </body>
    </html>

     -- 以上是一道纸上面试题,要求用递归算法写出 1,1,2,3,5,8 ... 计算到第 30 位的代码。

    当时写的类似下面:

    <!doctype html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>计算到第30位</title>
        <script type="text/javascript">
            var a = 1;
            var b = 0;
            var t = new Date()
            document.write('1 ' + a + '<br />')
            for(var i=1;i<30;i++){        
                var c = a + b;
                b = a;
                a = c;
                document.write((i + 1) + ' ' + a + '<br />')
            }
            document.write(' 计算耗时 ' + ((new Date()).getTime() - t.getTime())/1000.0 + ' 秒')
        </script>
    </head>
    <body style="color:red;300px;border-bottom:1px solid red">    
    </body>
    </html>

  • 相关阅读:
    40 修改了机器名,portal重装后,还需要做什么?
    39 路径分析小练习
    38 空间查询小练习
    面向对象一些概念简述
    Js函数基本介绍
    JS中的变量和数据类型
    js基础语法
    Css样式优先级
    对响应式布局的理解和认知
    关于Flex布局
  • 原文地址:https://www.cnblogs.com/z5337/p/7745722.html
Copyright © 2011-2022 走看看