Knowing that: x^2 - 4y^2 = (x - 2y)*(x + 2y)
I wrote the following code:
x = 450000005;
y = 225000002;
n = x * x - 4 * y * y;
m = (x - 2 * y) * (x + 2 * y);
console.log(n, m);
And the output is:
900000032 900000009
So what happens inside JavaScript that makes these two expressions have different results? (It doesn't happen for all numbers!)
Your first calculation is exceeding Number.MAX_SAFE_INTEGER
, which means it cannot be accurately represented. Using BigInt
s instead will produce the correct results.
console.log("Is 450000005 * 450000005 (x * x) safe?",
Number.isSafeInteger(450000005 * 450000005));
x = 450000005n;
y = 225000002n;
n = x * x - 4n * y * y;
m = (x - 2n * y) * (x + 2n * y);
console.log(n.toString(), m.toString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With