javascript 对两个整数之间的所有数字求和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30386084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sum all numbers between two integers
提问by jonplaca
OBJECTIVE
客观的
Given two numbers in an array, sum all the numbers including (and between) both integers (e.g [4,2] -> 2 + 3 + 4 = 9).
给定数组中的两个数字,将包括(和之间)两个整数的所有数字相加(例如 [4,2] -> 2 + 3 + 4 = 9)。
I've managed to solve the question but was wondering if there is a more elegant solution (especially using Math.max and Math.min) - see below for more questions...
我已经设法解决了这个问题,但想知道是否有更优雅的解决方案(尤其是使用 Math.max 和 Math.min) - 请参阅下文了解更多问题...
MY SOLUTION
我的解决方案
//arrange array for lowest to highest number
function order(min,max) {
return min - max;
}
function sumAll(arr) {
var list = arr.sort(order);
var a = list[0]; //smallest number
var b = list[1]; //largest number
var c = 0;
while (a <= b) {
c = c + a; //add c to itself
a += 1; // increment a by one each time
}
return c;
}
sumAll([10, 5]);
MY QUESTION(S)
我的问题
- Is there a more efficient way to do this?
- How would I use Math.max() and Math.min() for an array?
- 有没有更有效的方法来做到这一点?
- 我如何将 Math.max() 和 Math.min() 用于数组?
回答by jordiburgos
Optimum algorithm
最优算法
function sumAll(min, max) {
return ((max-min)+1) * (min + max) / 2;
}
回答by Josh Kuhn
var array = [4, 2];
var max = Math.max.apply(Math, array); // 4
var min = Math.min.apply(Math, array); // 2
function sumSeries (smallest, largest) {
// The formulate to sum a series of integers is
// n * (max + min) / 2, where n is the length of the series.
var n = (largest - smallest + 1);
var sum = n * (smallest + largest) / 2; // note integer division
return sum;
}
var sum = sumSeries(min, max);
console.log(sum);
回答by Semicolon
The sum of the first n integers (1 to n, inclusive) is given by the formula n(n+1)/2. This is also the nth triangular number.
前 n 个整数(1 到 n,包括端点)的总和由公式 n(n+1)/2 给出。这也是第 n 个三角形数。
S1 = 1 + 2 + ... + (a-1) + a + (a+1) + ... + (b-1) + b
= b(b+1)/2
S2 = 1 + 2 + ... + (a-1)
= (a-1)a/2
S1 - S2 = a + (a+1) + ... + (b-1) + b
= (b(b+1)-a(a-1))/2
Now we have a general formula for calculating the sum. This will be much more efficient if we are summing a large range (e.g. 1 million to 2 million).
现在我们有了一个计算总和的通用公式。如果我们对一个大范围(例如 100 万到 200 万)求和,这将更加有效。
回答by Tarandeep Singh
Here is a one liner recursive program solution of SumAll using es6.
这是使用es6的SumAll的单线性递归程序解决方案。
const SumAll = (num, sum = 0) => num - 1 > 0 ? SumAll(num-1,sum += num) : sum+num;
console.log(SumAll(10));
Note :: Although the best Example is using the Algorithm, as mentioned above. However if the above can be improved.
注意 :: 虽然最好的例子是使用算法,如上所述。但是如果以上可以改进。