Sum All Numbers in a Range

//自己的思路

function sumAll(arr) {
  let sum= 0;
  for(let i= Math.min(...arr); i<= Math.max(...arr); i++){
    sum+= i
  }
  return sum;
}

sumAll([1, 4]);
//数学公式版:N个头尾数相乘
function sumAll(arr) {
  let start= arr[0], end= arr[1], sum= 0  
  let isAnEvenNumberOfCount= Math.abs(start-end+1) % 2 === 0
  if(isAnEvenNumberOfCount) {
    //参与求和的数字的个数是偶数
    sum= (start+end) * (Math.ceil(Math.abs(start-end)/2))
  }else {
    //参与求和的数字的个数是奇数
    sum= (start+end)* (Math.ceil(Math.abs(start-end)/2)) + ((start+end)/2)
  }
  return sum
}
sumAll([5, 19]);

总结公式草纸:

别人家的孩子 QAQ

const sumAll = arr => {
  // Buckle up everything to one!
  const startNum = arr[0];
  const endNum = arr[1];

  // Get the count of numbers between the two numbers by subtracting them and add 1 to the absolute value.
  // ex. There are |1-4| + 1 = 4, (1, 2, 3, 4), 4 numbers between 1 and 4.
  const numCount = Math.abs(startNum - endNum) + 1;

  // Using Arithmetic Progression summing formula
  const sum = ((startNum + endNum) * numCount) / 2;
  return sum;
};

//归纳现象为公式,带入数字验证。这就科学了,不一定非得领悟什么

//1. 两数相减,结果的绝对值+1,就是参与求和的数量
//2. (头、尾数相加)* 参与数量 / 2 = start+ start+1 + ... + end = 和
	3+4+5 = 4+4+4 = 8/2+8/2+8/2 = 3*(8/2) = 8*3/2 = (3+5)*3/2 = (start+end)*3/2