There is such a function, how to modify it to 2 values, so that you can count from the number num1 to the number num2

function sumTo(n) { if (n == 1) return 1; return n + sumTo(n - 1); } alert( sumTo(100) ); 
  • normal for loop. What are your difficulties with him? - splash58
  • so the fact of the matter is that the cycle is not necessary, it is necessary with the use of such a function without a cycle - vasyajidko
  • So, Gauss is not on you) - vp_arth

3 answers 3

Almost the same:

 function sumFromTo(from, to) { if (from > to) return sumFromTo(to, from); if (to===from) return from; return from + sumFromTo(from+1, to); } console.log(sumFromTo(1, 100)); // 5050 console.log(sumFromTo(100, 1)); // 5050 

You can slightly reduce the depth of the stack:

 function sumFromTo(from, to) { if (to === from) return from; if (to === from + 1) return from + to; return from + to + sumFromTo(from + 1, to - 1); } console.log(sumFromTo(1, 100)); // 5050 console.log(sumFromTo(1, 99)); // 4950 

     function sumTo(a,n){ if(n==a) return a; return n + sumTo(a,n-1); } alert(sumTo(4,9)); 

      Is recursion required? But you can just because:

       function sumFromTo(n1, n2) { return (n1 + n2) * (n2 - n1 + 1) / 2; } console.log(sumFromTo(1, 99)); console.log(sumFromTo(2, 100));