首页 > 代码库 > 递归题

递归题

公园里面有200个桃子,每天吃掉一半,扔掉一个烂的,第6天剩余多少桃子

(迭代法)

当天的数量=(上一天的数量/2)-1

var sl = 200;
	for(var i=0;i<6;i++){
		sl = parseInt(sl/2)-1;
	}
	alert(sl);

公园里有一堆桃子,猴子每天能吃掉一半,扔掉一个烂的,发现第6天的时候剩余1个桃子,问刚开始有多少桃子

当天的剩余量= (下一天的剩余量+1)*2 

迭代:

var sl=1;
 for (var i=0;i<6;i++){
	   sl=(sl+1)*2; 
	 }
	 alert(sl);

  

递归:

函数明确:给一个天数,返回该天剩余的桃子数量

function shuLiang(ts){
	      
	           if( ts==6){
				   return 1;
				   }
				   return (shuLiang(ts+1)+1)*2
				 }
	 alert(shuLiang(1));

  

 函数运行过程:

0
     function shuLiang(0){
		 
		 return (shuLiang(0+1)+1)*2
		 }
	 
	 	 
1	 
	 function shuLiang(1){
		 return (shuLiang(1+1)+1)*2
		 }
		 
2		 
	 function shuLiang(2){
		 return (shuLiang(2+1)+1)*2
		 }
		 
3		 
	 function shuLiang(3){
		 return (shuLiang(3+1)+1)*2
		 }
		 
4		 
     function shuLiang(4){
		 return (shuLiang(4+1)+1)*2
		 }
		 
5		 
	function shuLiang(5){
		return (shuLiang(5+1)+1)*2
		}
6		
		
	function shuLiang(6){
		return (shuLiang(6+1)+1)*2
		}
		alert(1);
		
		
5		
	function shuLiang(5){
		return (shuLiang(5+1)+1)*2
		}
		alert(4);
		
4		
	function (4){
		return (shuLiang(4+1)+1)*2
		}
		alert(10);
		
3		
	function(3){
		return (shuLiang(3+1)+1)*2
		}
		alert(22);
		
2		
	function shuLiang(2){
		return (shuLiang(2+1)+1)*2
		}
		alert(46);
		
1		
	function shuLiang(1){
		
		return (shuLiang(1+1)+1)*2
		}
		alert(94);
		
0		
	function shuLiang(0){
		return (shuLiang(0+1)+1)*2
		}
		alert(190);

  

递归题