kidlogic kidlogic - 4 months ago 48
Javascript Question

Sum all numbers between two integers

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?


Answer
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);