`

js递归题

    博客分类:
  • js
 
阅读更多
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.deng.testjs.model.Person"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript">
	  
	  /**
	          利用递归实现:
	        1 1 2 3 5 8 13 21 34 根据规律(从第3项开始后项等于前面两项之和),请第30项的值
	  */
	  
	  function test(){
	    alert("非递归值为=" + cal(9));
	    alert("递归值为=" + calcForRecursive(9));
	    
	  }
	  
	  /**
	        不用递归实现
	  */
	  function cal(number){
        if(number <= 2){
         return 1;
        }
        
	    var a1 = 1;
	    var a2 = 1;
	    var result;
	    var temp;
	    
	    for(var i = 2; i < number; i++){
	      result = a1 + a2;
	      temp = a2;
	      a2 = result;
	      a1 = temp; 
	    }
	    
	    return result;
	  }
	  
	  
	  function calcForRecursive(number){
	    if(number <= 2){
           return 1;
        }
        
        return recursiveHandler(1, 1, 2,number);
        
	  }

	  function recursiveHandler(a1,a2,count,number){
	      var result = a1 + a2;
	      count++;
	      if(count == number){
	         return result;
	      }else{
	        return recursiveHandler(a2,result,count,number);
	      }
	  }
	
	
	</script>
	
  </head>
  
  
  <body>
    This is my JSP page. <br>
    <input type="button" onclick="test()" value="test">
  </body>
</html>
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics