It seems that the compiler is not going into the for loop.The sum of the array is to calculated.SumAll([1,4]) should return 10(1+2+3+4) as output.
function sumAll(arr) {
//return Math.max.apply(Math,arr);
//return Math.min.apply(Math,arr);
// return "0";
var sum=arr.reduce(function(a,b){
for(var i=Math.min.apply(Math,arr);i<=Math.max.apply(Math,arr);i++){
return a+b;
}
},0);
//return sum;
}
sumAll([1, 4]);
You can try something like this:
Note: your array has limits of range, so you should use these values for loop and use
i
to calculate sum.Sample
For loop
Formula based
Your Code's explanation
There are 2 ways to do this.
n1 + (n1 + 1) + ... + n2 = n2(n2 + 1) / 2 - n1(n1 - 1) / 2
. Time complexity: O(1)Obviously for numbers with large range, the first way is much faster.
You don't need a
reduce
because you don't have an array to reduce. You can however keep the for loop and accumulate the sum by addingi
tosum
on each iteration. The problem was that you:return
ing immediately out of the for loop, so no accumulation of sum was occuring.Here's what the code should look like:
You could use directly the values from the array, without reduce.
It seems no one wants to use the formula for the sum of the first N natural numbers: