DEV Community

NJOKU SAMSON EBERE
NJOKU SAMSON EBERE

Posted on • Updated on

Algorithm 202: 3 Ways to Sum a Range of Values

Given an array of two element as minimum and maximum values ([min, max]), how can you sum up all the values between the min and max values?


rangeSum([1, 9]) // 45

rangeSum([5, 12]) // 68

Enter fullscreen mode Exit fullscreen mode

We are about to dive into 3 ways to achieve this!

Prerequisite

To flow with this article, it is expected that you have basic understanding of javascript's array methods.

Let's Sum a Range of values using:

  • while...loop
      function rangeSum(array) {
        let result = 0;
        let i = 0;

        while (i < array[1]) {
          result = result + (i + array[0]);
          i++;
        }

        return result;
      }
Enter fullscreen mode Exit fullscreen mode
  • for...loop
      function rangeSum(array) {
        let result = 0;

        for (let i = array[0]; i <= array[1]; i++) {
          result = result + i;
        }

        return result;
      }
Enter fullscreen mode Exit fullscreen mode
  • for...loop, push(), reduce()
      function rangeSum(array) {
        let rangeArray = [];

        for (let i = array[0]; i <= array[1]; i++) {
          rangeArray.push(i);
        }

        let result = rangeArray.reduce((acc, char) => acc + char);

        return result;
      }
Enter fullscreen mode Exit fullscreen mode

Conclusion

There are many ways to solve problems programmatically. You are only limited by your imagination. Feel free to let me know other ways you solved yours in the comment section.

If you have questions, comments or suggestions, please drop them in the comment section.

Up Next: Algorithm 202 (My Interview Question): Grouping Anagrams in 3 Ways

You can also follow and message me on social media platforms.

Twitter | LinkedIn | Github

Thank You For Your Time.

Top comments (5)

Collapse
 
ganeshshetty195 profile image
Ganesh Shetty • Edited

This also works pretty well.

function findSum([min, max]) {
var sum = 0;
while (min <= max) {
sum += min;
min++
}
return sum;
}
console.log(findSum([5, 12]));

Collapse
 
kaykleinvogel profile image
Kay Kleinvogel

I tried to implement the algorithm myself and came up with a solution that is utilizing the formula for sums by Gauss.

IDK how to explain the equation but it would look like this:

Sum=i=1maxii=1mini=max(max+1)2min(min+1)2 Sum=\sum_{i=1}^{max}i - \sum_{i=1}^{min}i = \frac{max\cdot (max+1)}{2}-\frac{min\cdot(min+1)}{2}

I implemented this in typescript to see if it works:

const rangeSum = (boundaries: Array<number>): number => {
    const startingPoint = boundaries[0];
    const endPoint = boundaries[1];
    const sum = gaus(endPoint) - gaus(startingPoint - 1);
    return sum;
};

const gaus = (limit: number): number => {
    const gaus_sum = (limit * (limit + 1)) / 2;
    return gaus_sum;
};

The startingPoint - 1 is adjusting that the formula would be excluding the min and we want to include it. In general it seems to be working quiet well.

The advantage here also is that it only has to execute 2 operations no matter how large the span is.
This would decrease the time complexity to O(1). Which is quiet nice.

Collapse
 
ebereplenty profile image
NJOKU SAMSON EBERE

Kay, thank you for your suggestion. This is how I did it with javascript:

function rangeSum(array) {
  let max = array[1];
  let min = array[0];

  let maxManipulation = (max * (max + 1))/2;
  let minManipulation = (min * (min + 1))/2;

  return maxManipulation - minManipulation + array[0];
}

So, I had to add the lower boundary (min value) to the final answer to make it work properly.

Collapse
 
kaykleinvogel profile image
Kay Kleinvogel • Edited

Yeah. You either have to add the min value or subtract minManipulation(array[0]-1) because otherwise it will exclude the lower boundary. So I corrected the formula to reflect this change (just in case anybody is interested in this).

i=minmaxi=i=1maxii=1mini+mini=minmaxi=max(max+1)2min(min+1)2+min \sum_{i=min}^{max}i=\sum_{i=1}^{max}i-\sum_{i=1}^{min}i + min \newline \sum_{i=min}^{max}i= \frac{max\cdot (max+1)}{2}-\frac{min\cdot(min+1)}{2}+min
Thread Thread
 
ebereplenty profile image
NJOKU SAMSON EBERE

Looking Good 💪