Factorial sum in JavaScript

0

I am trying to create a function that takes two parameters (a, b) and adds them recursively, from a to b including b, returning the result of the sum. In this way (1, 4) returns 10 (1 + 2 + 3 + 4).

In my algorithmic design the function below should work but it does not:

var sumAll = function(a, b) {

  let sum = a;    

  for (let index = a; index <= b; index++) {   
      sum += index;        
  }
  return sum;
}

console.log(sumAll(1, 4)); // devuelve 11

What is missing from the logic of my program?

    
asked by ChairoDev 11.05.2018 в 02:03
source

1 answer

0

You're adding twice. The correct way would be like this:

var sumAll = function(a, b) {

  let sum = 0;    

  for (let index = a; index <= b; index++) {   
      sum += index;        
  }
  return sum;
}
    
answered by 11.05.2018 / 02:05
source