skip to Main Content

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


  1. So, it looks like your example includes values between x and y, and runs until y has been decremented until it equals x, so let’s work based off of that.

    Easy to read version

    function rangeSum(start, end) {
      let total = 0;
      let currentEnd = end;
      let current = start;
    
      while (currentEnd >= start) {
        while (current <= currentEnd) {
          // add to the sum
          total += current;
          // step the current value up
          current += 1;
        }
        // step the end value down
        currentEnd -= 1;
        // reset the current value to start
        current = start;
      }
    
      return total;
    }
    
    console.log(rangeSum(0, 6));
    // > 56
    

    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 at 1 (or 0, since adding 0 doesn’t change the sum):

    Tetrahedral Numbers Forumla

    function tetrahedral(n) {
      return (n * (n + 1) * (n + 2)) / 6;
    }
    
    console.log(tetrahedral(6));
    // > 56
    

    Hope this helps. 🙂 Thanks for the fun rabbit trail.

    Login or Signup to reply.
  2. function rangeSum(start, end) {
      let sum = 0;
    
      while (start <= end) {
        for (let i = start; i <= end; i++) {
          sum += i;
    
          if (i === end) end--;
        }
      }
    
      return sum;
    }
    
    console.log("0~3 : ", rangeSum(0,3)); // 10
    console.log("3~5 :", rangeSum(3,5)); // 22
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search