查找连续数字数组的总和

时间:2019-12-27 17:42:58

标签: javascript arrays numbers

我如何找到连续数字的总和,例如:

  • 1 + 2 + 3 = 6

  • 3 + 5 + 7 + 9 = 24

当我只知道数字的第一个,最后一个和增量时?

这是它的外观:

function sumOfCon(f, l, i) {
  //...
}
console.log(sumOfCon(1, 3, 1));
console.log(sumOfCon(3, 9, 2));

我没有“我尝试过的方法”,因为我在下面发布了答案。

4 个答案:

答案 0 :(得分:1)

经检查后看起来像这样

function sumOfCon(f, l, i) {
  const parts = (l - f) / i
  if (Math.floor(parts) !== parts) return undefined
  return (l + f) * (parts / 2 + 0.5) 
}

答案 1 :(得分:1)

function sumOfCon(first, last, inc) {
  let sum = 0;
  for (let i = first; i <= last; i = i + inc) {
      sum += i;
  }
  return sum;
}

console.log(sumOfCon(1, 3, 1));
console.log(sumOfCon(3, 9, 2));
console.log(sumOfCon(3, 5, 3));

答案 2 :(得分:0)

您可以使用以下功能添加数字。 (下面的说明)

当数字是1 + 3 + ... 8时,这是行不通的,因为这几乎是不可能的。

function sumOfCon(f, l, i) { //first, last, increment
  if ((f + l) % i !== 0) return sumOfCon(f, l - ((f + l) % i), i);
  return (f + l) * (l - f + i) / (2 * i);
  /*a simplified version is: (l*l-f*f+i*(f+l))/(2*i)
   **Explanation to the function**
   *For 1, 5, 1, the numbers are 1, 2, 3, 4, 5, 6.
   *1 + 6 is 7, and so is 2 + 5, and 3 + 4.
   *This means that multiplying (1 + 6) by 3 gives us the answer.
   *You can get 3 by taking the number of numbers and dividing by 2.
   *But if the increment is not 1, like 5, 7, 9, it is trickier.
   *First, you add 5 + 9 = 14.
   *14 × 1.5 gives us the answer, because there are 3 numbers and 3
   *divided by 2 is 1.5
   *You can get the amount of numbers by doing (l - f + 1) if the
   *increment is 1.
   *If the increment is not 1, you can do (l - f + i) / i.
   *Finally, you divide by 2 to get the sum.
  */
}
console.log(sumOfCon(1, 3, 1));
console.log(sumOfCon(3, 9, 2));
console.log(sumOfCon(0, 26, 2));
console.log(sumOfCon(1, 6, 2)); // 1 + 3 + 5

答案 3 :(得分:0)

let sumOfCon= (...a) => a.reduce((a,b)=>a+b)

sumOfCon(1,2,3) //6
sumOfCon(1,2,3,4,5) //15

看这个https://www.youtube.com/watch?v=xKmtUW9VKVA&t=11s