Courses / DSA Patterns for Working Engineers / Chapter 29
Module 9 · Bits, maths and mixed practice · Chapter 29 of 39
Math and Geometry: Precision, Primes, Powers and Points
Builds on Intervals: Merging, Inserting and Counting Overlaps and Bitwise Manipulation: Masks, XOR and the 32-Bit Trap. Next up: Mixed Practice: Pick the Pattern Under Time.
Part 1 · Introduction to math in code
Exact integers and where they end
Prices in paise, invoice totals, route coordinates and plot sizes look like simple arithmetic, yet JavaScript numbers lose exactness past 2 to the power 53 and bitwise tricks wrap at 32 bits. Keeping arithmetic exact, and testing points and rectangles with integers instead of fractions, avoids both traps.
Every JavaScript number is a 64-bit floating-point value. It has 53 bits for the digits, so every integer up to 2 to the power 53 minus 1 is stored exactly. That limit is Number.MAX_SAFE_INTEGER, which is 9007199254740991. Beyond it, neighbouring integers are no longer all representable, and a sum or product is silently rounded to the nearest value that is. The method Number.isSafeInteger(x) tells you whether an integer is inside the exact range.
This matters because many counting problems ask for an answer modulo a large prime such as 1,000,000,007, which keeps results small. A product of two residues below that prime can be close to 10 to the power 18, far past the exact range. The run below multiplies two nine-digit numbers with plain numbers and with BigInt, and takes the remainder in both.
console.log(Number.MAX_SAFE_INTEGER, 2 ** 53 === 2 ** 53 + 1) const a = 987654321 const b = 876543210 const m = 1_000_000_007 console.log('number:', (a * b) % m) console.log('bigint:', (BigInt(a) * BigInt(b)) % BigInt(m)) console.log(Number.isSafeInteger(a * b))