在JavaScript中使用循环查找连续整数的总和 [英] Find the sum of consecutive whole numbers w/o using loop in JavaScript

查看:76
本文介绍了在JavaScript中使用循环查找连续整数的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来进行如下计算:

I'm looking for a method to do calculations like:

function sumIntegerUpTo(number) {
  return 1+2+3+...+number;
}

如果你传递数字 as 5 函数应返回 1 + 2 + 3 + 4 + 5 的总和。我想知道是否可以不循环。

If you pass number as 5 function should return the sum of 1+2+3+4+5. I'm wondering if it's possible to do without loops.

推荐答案

function sumIntegerUpTo(number) {
    return (1 + number) * number / 2;
}

我可以想到两种简单的方法来记住这个公式:

I can think of two easy ways for me to remember this formula:


  • 考虑从序列的两端添加数字:1和n,2和n-1,3和n-2,这些小额中的每一个最终都等于n + 1。两端将在序列的中间(平均)结束,因此总共应该有n / 2个。所以sum =(n + 1)*(n / 2)。

  • Think about adding numbers from both ends of the sequence: 1 and n, 2 and n-1, 3 and n-2, etc. Each of these little sums ends up being equal to n+1. Both ends will end at the middle (average) of the sequence, so there should be n/2 of them in total. So sum = (n+1) * (n/2).

平均值之前有多少个数(即(1 + n)/ 2)因为有后,并且添加一对与该平均值等距的数字总是导致平均值的两倍,并且有n / 2对,所以sum =(n + 1)/ 2 * 2 * n / 2 =(n + 1)/ 2 * n。

There are as many number before the average (which is (1+n)/2) as there are after, and adding a pair of numbers that are equidistant to this average always results in twice the average, and there are n/2 pairs, so sum = (n+1)/2 * 2 * n/2 = (n+1)/2*n.

您可以相当轻松地将上述推理扩展到另一个起点数字,给你:总和(从a到b的数字,包括在内)=(a + b)/ 2 *(b-a + 1)。

You can fairly easily extend the above reasoning to a different starting number, giving you: sum(numbers from a to b, inclusive) = (a+b)/2*(b-a+1).

这篇关于在JavaScript中使用循环查找连续整数的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆