DEV Community

Discussion on: Algorithm 202: 3 Ways to Sum a Range of Values

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 💪