Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
76
rated 0 times [  77] [ 1]  / answers: 1 / hits: 25243  / 9 Years ago, thu, may 21, 2015, 12:00:00

OBJECTIVE



Given two numbers in an array, sum all the numbers including (and between) both integers (e.g [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...



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)




  1. Is there a more efficient way to do this?

  2. How would I use Math.max() and Math.min() for an array?


More From » javascript

 Answers
63
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);

[#66507] Tuesday, May 19, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
albert

Total Points: 652
Total Questions: 105
Total Answers: 108

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;