递归 从n加到m

<?php
 //n +(n+1)+...+(m-1)+m(n>0,m>n)
 function sum($n,$m){
   if($m<=$n){
     return $n;
   }
  return sum($n,$m-1)+$m;
 }
 echo sum(1,100);
 //执行流程如下
 #sum(1,100)=>sum(1,99)+100=>sum(1,98)+99....=>sum(1,1)
 //最终数据被替换完毕 故成了从1加到100

 

点赞