Search code examples
javascriptcalculatorarithmetic-expressionsinteger-arithmetic

What is the best way to realize high precision arithmetic calculations in JavaScript?


I'm doing an algorithm that checks if a number is prime for college, but I came across a connotation and calculation problem where I need to consider large numbers.

One of them was solved with the support of BigInt(), however in arithmetic calculations from a certain number of decimal places it ends up losing precision and consequently returning false true.

For example, multiplying 2 numbers ending in 1,3,7,9 always results in a number ending in 1,3,7,9, but from 3**34 onwards the calculations start to lose precision.

Is there any efficient way to solve this problem in JavaScript?

console.log(`
  ${3**32}, ${BigInt(3**32)}
  ${3**33}, ${BigInt(3**33)}
  ${3**34}, ${BigInt(3**34)}
  ${3**35}, ${BigInt(3**35)}
  ${3**37}, ${BigInt(3**37)}

  ${3*1597*3237*5549}, ${BigInt(3*1597*3237*5549)}
  ${3*1597*3237*5549*13213}, ${BigInt(3*1597*3237*5549*13213)}
  ${3*1597*3237*5549*13213*4543}, ${BigInt(3*1597*3237*5549*13213*4543)}
`);


Solution

  • BigInt type numbers are recommended for this type of operation. I believed that BigInt() was just a conversion method, but is a numerical unit as well.

    calculations must also be done using the same number format, and if a division results in a fraction, it is rounded down.

    console.log(`
      ${3n**32n}
      ${3n**33n}
      ${3n**34n}
      ${3n**35n}
      ${3n**37n}
    
      ${3n*1597n*3237n*5549n}
      ${3n*1597n*3237n*5549n*13213n}
      ${3n*1597n*3237n*5549n*13213n*4543n}
    
      ${1n/3n}
      ${2n/3n}
    `);