Comment

Comment by inbx0

Well, for one thing, if you copied the numbers from the example as they are defined, then JS will be dealing with simple floating point numbers and actually gets the answer wrong (but gets there fast!). The answer is beyond 5E+17 but JS's Number.MAX_SAFE_INTEGER is only 9E+15. The results start getting weird after that.

To get the correct answer, we need to convert some of the numbers to BigInts

  var result = 0n

  function main() {
    var sum = 0n
    var i = 1
    while (i <= 1000000000) {
        sum = sum + BigInt(i)
        i = i + 1
    }
    result = sum
  }

  main()
but after that the result is not quite so impressive anymore

  Now using node v15.6.0 (npm v7.4.0)
   time node index.js
  node index.js  51.50s user 0.40s system 103% cpu 50.072 total
parent inbx0 5 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton