Code:
var sum_with_formula = function (n) {
return n/2*(n+1);
}
var sum_with_loop = function (n) {
var sum = 0;
for (var i=1; i<=n; i++) {
sum = sum + i;
}
return sum;
}
var n = 1000000000;
const assert = require('assert');
assert.equal(sum_with_formula(n), sum_with_loop(n));
Result:
assert.js:85
throw new assert.AssertionError({
^
AssertionError: 500000000500000000 == 500000000067109000
Why is there a difference between calculations with iteration and calculations by formula?
But if n = 100000000, the result is correct.
If n = 200000000, the result is wrong:
AssertionError: 20000000100000000 == 20000000067108864
I am using NodeJS v6.9.2.
via Fakhri Izzudin
No comments:
Post a Comment