Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum all numbers between two integers

Tags:

javascript

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?
like image 977
jonplaca Avatar asked May 21 '15 23:05

jonplaca


People also ask

How do you find the sum of all integers between two numbers in C?

printf("Enter two integers: "); scanf("%d %d", &number1, &number2); Then, these two numbers are added using the + operator, and the result is stored in the sum variable. Finally, the printf() function is used to display the sum of numbers. printf("%d + %d = %d", number1, number2, sum);

What is the sum of all the integers?

The formula to calculate the sum of integers is given as, S = n(a + l)/2, where, S is sum of the consecutive integers n is number of integers, a is first term and l is last term.

How do you sum all numbers in a range?

Here's a formula that uses two cell ranges: =SUM(A2:A4,C2:C3) sums the numbers in ranges A2:A4 and C2:C3. You'd press Enter to get the total of 39787.


1 Answers

Optimum algorithm

function sumAll(min, max) {
    return ((max-min)+1) * (min + max) / 2;
}
like image 63
jordiburgos Avatar answered Oct 05 '22 23:10

jordiburgos