首页 > 代码库 > Sum All Numbers in a Range

Sum All Numbers in a Range

function sumAll(arr) {
  //return 1;
  var result = 0,
      a = Math.max(arr[0],arr[1]),
      b = Math.min(arr[0],arr[1]);
  while (a >= b){
    result += b;
    b++;
  }
  return result;
}

sumAll([1, 4]);

function sumAll(arr) {
  //return 1;
  return (arr[0] + arr[1]) * (Math.abs(arr[0] - arr[1]) + 1) / 2;
}

sumAll([1, 4]);

  公式法

function sumAll(arr) {
  var arryA=[];
   var max=Math.max.apply(null,arr);
   var min=Math.min.apply(null,arr);
   var sum=0;
   var sumFun=function(max,min){
      for(var i=0;i<(max-min+1);i++){
         arryA.push(min+i);
      }
      console.log(arryA);
      var value=http://www.mamicode.com/arryA.reduce(function(previousValue,currentValue){>

  

 

Sum All Numbers in a Range