0

I need to perform arithmetical operations with large numbers in JS, in this particular case it is:

(1827116622 / 6) * 251772294

The expected result is 76669557221078478 but I am getting 76669557221078460 because of integer overflow.

The environment does not allow including any libraries. Is there a workaround to handle calculations like this?


Why I am doing so: I am trying to find the least common multiplier for these numbers using the following formula:

LCM(, )·GCD(, ) = · where LCM is Least Common Multiplier and GCD is Greatest Common Divisor.

My calculation is ( a / gcd ) * b.

Igor Skoldin
  • 730
  • 3
  • 12
  • 25
  • 3
    Use a big integer library. Google "Javascript big integer" – Barmar Aug 25 '16 at 05:25
  • There is a problem, I use it in an environment that does not allow including libraries. Updated my question to clarify this – Igor Skoldin Aug 25 '16 at 07:04
  • You need to use [arbitrary-precision arithmetic](https://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic), there are some good small libraries out there that are well tested, [big.js](https://github.com/MikeMcl/big.js/) would be suitable for your calculations by the looks of it. Can't include the library, then look at the code and take what you need (/ and *). – Xotic750 Aug 25 '16 at 07:39
  • use [browserify](https://github.com/substack/node-browserify#usage) so as you are planning to use node. After you file is ready, go to the command line and ' $ browser --node yourFile.js > build.js ' build.js should work in your environment. – sonali Aug 26 '17 at 21:13

1 Answers1

0

Numbers in JavaScript are represented by 64-bit doubles, which give you 53-bit integer part, if you go above 53 bits your numbers "become doubles", so you get rounding.

If you to work with integers larger than 53 bits, you need a custom solution like other wrote in comments.

Vad
  • 4,052
  • 3
  • 29
  • 34