Reputation: 13
So I was trying to compare the two functions and I realized that when you pass 1000000000
as n
to both functions they don't return the same value, even though they should. The sum function returns 500000000067109000
when the correct answer is 500000000500000000
.
Why is this happening?
function sum(n) {
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += i;
}
return sum
}
function sum2(n) {
return n * (n + 1) / 2
}
console.log(sum(1000000000)); //returns 500000000067109000 (incorrect)
console.log(sum2(1000000000)); //returns 500000000500000000 (correct)
Upvotes: 0
Views: 44