How can I calculate the sum of all the values in the range between x and y that were output when the function executes so that after each complete loop it repeats decrementing y by one until y will not reach x.
For example: rangeSum(0, 3); --> result: 10 (0+1+2+3+0+1+2+0+1+0)
My code:
function rangeSum(x, y) {
let sum = 0;
for (i = x; i <= y; sum += i++);
sum += i + i--;
return (sum);
};
I just don’t know how to do it because I’m new to JS.
2
Answers
So, it looks like your example includes values between
x
andy
, and runs untily
has been decremented until it equalsx
, so let’s work based off of that.Easy to read version
Digging further
I was playing around with the output of this function for fun and decided to search around a bit to see if this specific pattern of output had an existing formula. Sounds like according to this, you’re looking at wanting the formula for tetrahedral numbers. If that’s the case, there’s a much more concise formula if you consider
x/start
from our original example to be fixed at1
(or0
, since adding0
doesn’t change the sum):Tetrahedral Numbers Forumla
Hope this helps. 🙂 Thanks for the fun rabbit trail.