Sum all numbers between two whole numbers

TARGET

Given two numbers in an array, sum all the numbers including (and between) both integers (eg [4,2] → 2 + 3 + 4 = 9 ).

I was able to resolve 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 DECISION

//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 do I use Math.max () and Math.min () for an array?
+3


source to share


4 answers


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

      



+7


source


Optimal algorithm



function sumAll(min, max) {
    return ((max-min)+1) * (min + max) / 2;
}

      

+13


source


The sum of the first n integers (from 1 to n, inclusive) is given by the formula n (n + 1) / 2. It is also the nth triangular number.

         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

      

We now have a general formula for calculating the sum. It will be much more efficient if we sum up a large range (for example, 1 to 2 million).

+2


source


Following is SumAll's one-time recursive software solution using es6.

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.

0


source







All Articles