After my discussion of JavaScript’s numeric limitations when working with integers, I was curious. There must be some integer that’s the biggest one that JavaScript can represent.
A brute force method (my favorite kind) would simply increment a variable and see when it stops going up. Add one. Add one. Add one. Stuck.
That number is so large, though, that even I didn’t have the patience to wait for the loop to end. So I broke the problem up into two pieces.
First I set a variable to 1. I keep doubling it until I find a number that is the same as that number plus one. That’s my high limit and half that number is valid.
Then I do a binary search inside that range. The code looks like this:
a=1; b=2; //find one that fails while (a!=b) { old=a; a+=a; b=a+1; } //do binary search low=old; high=a; while (high-low>1) { mid=parseInt((low+high)/2,10); a=mid; b=a+1; if (a==b) { high=mid; } else { low=mid; } } console.log(high);
The answer is 9007199254740992. Something over 9 quadrillion. Makes more sense why it would be a limit when you look at the number in hexadecimal. That’s 0x020000000000000.
That’s right. JavaScript can tell the difference between 9007199254740991 and 9007199254740992, but it thinks that 9007199254740992 and 9007199254740993 are the same. That falls out from the IEEE-754 double-precision floating-point spec that JavaScript uses to represent all numbers.
Remember that next time you want to write a for loop that counts to 10 quadrillion–it’s an infinite loop. You’ll never get there.