1

I am trying to understand why I am not able to calculate the right modulo using JavaScript. The operation I have tried is:

Wrong answer

28493595674446332150349236018567871332790652257295571471311614363091332152517 % 6 = 4

The result should be 1.

28493595674446332150349236018567871332790652257295571471311614363091332152517 % 6 = 1

I have tried to convert this number to BN but unfortunately I always get the same answer. However if you use wolfram alpha or another math software it returns the right answer.

What's going on? What have I been doing wrong?

Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
ARR
  • 23
  • 2
  • 2
    Do you mean modulo? – putvande Feb 12 '20 at 21:31
  • 1
    It's not the modulo operator, but the remainder operator. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder – evolutionxbox Feb 12 '20 at 21:32
  • Also.. that number is way too big for JavaScript. – putvande Feb 12 '20 at 21:33
  • 5
    `28493595674446332150349236018567871332790652257295571471311614363091332152517 > Number.MAX_SAFE_INTEGER // true` - It's wayyy to big for normal numbers. Consider using a BigInt instead. – evolutionxbox Feb 12 '20 at 21:33
  • 3
    Use [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt), here is an example `BigInt('28493595674446332150349236018567871332790652257295571471311614363091332152517') % BigInt(6)` – Titus Feb 12 '20 at 21:34
  • just use bigInt `28493595674446332150349236018567871332790652257295571471311614363091332152517n % 6n === 1n` – balexandre Feb 12 '20 at 21:35
  • 1
    @Titus BigInt literals can be made without the function. `6n` is a big int. – evolutionxbox Feb 12 '20 at 21:36
  • 3
    @evolutionxbox Using the function illustrates better what is going on there. – Titus Feb 12 '20 at 21:37

1 Answers1

3

The integer number range in JavaScript is +/- 9007199254740991 (Number.MAX_SAFE_INTEGER). Your number is simply out of range for JS.

You can also use the BigInt notation to get the right answer. 28493595674446332150349236018567871332790652257295571471311614363091332152517n % 6n

See What is JavaScript's highest integer value that a number can go to without losing precision?

Saeed D.
  • 1,125
  • 1
  • 11
  • 23
  • 3
    For clarity, the `n` suffix at the end of the number tells the interpreter that the preceding number is a `bigint`. –  Feb 12 '20 at 22:12