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?
ran...
For further actions, you may consider blocking this person and/or reporting abuse
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]));
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:
I implemented this in typescript to see if it works:
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.
Kay, thank you for your suggestion. This is how I did it with
javascript
:So, I had to add the lower boundary (min value) to the final answer to make it work properly.
Yeah. You either have to add the
min
value or subtractminManipulation(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).Looking Good 💪