Modulo% with a large number - Infinity error - Javascript

Is there a trick to getting the module of large numbers in Javascript. I get infinity with modulo(7, 16971, 25777) 7 ^ 16971mod25777 = NaN

 function modulo (n, p, m){ var x = Math.pow(n, p); var y = m; var z = x%y; alert(x); return z; } 
+6
source share
4 answers

There is a mathematical β€œtrick” that you can use if you can assume that all parameters are integers .

Consider the following modular operation:

(a * x + y)% x

Obviously, part a * x can be dropped and the following is true:

(a * x + y)% x = y% x

With this in mind, we can assume that a large number is just * x + y, and we can execute the module at any stage and as often as we like to get the desired result, do the following:

 function modulo (n, p, m){ var result = 1; while(p--) { result = (result * n) % m; } return result; } console.log(modulo(7, 16971, 25777)); 
+9
source

JavaScript numbers are stored as 64-bit floats .

Math.pow(7, 16971) has an Infinity value because this value is too large for this view. In particular, it is larger than Number.MAX_VALUE , which is 1.7976931348623157e+308 .

The largest safe integer is Math.pow(2, 53) - 1) , aka Number.MAX_SAFE_INTEGER .

To work with large integers, you can use an integer size library of any size, for example big-integer :

 const result = bigInt(7).modPow(16971, 25777); console.log(result.value); // 857 

Jsfiddle

+3
source

You probably want to look into a large number of libraries like big.js to do this. It has a mod() function to handle large numbers and more floating point precision.

From the manual:

 1 % 0.9 // 0.09999999999999998 x = new Big(1) x.mod(0.9) // '0.1' 
+1
source

Please try this, it should work for you ...

  <script src="http://peterolson.github.com/BigInteger.js/BigInteger.min.js"></script> <script> function modulo(n, p, m) { var x = bigInt(n).pow(p); var y = m; var z = bigInt(x).mod(y); alert(x); alert(z); return z; } modulo(7, 16971, 25777); </script> 

X value = (1468387901625157 ... 36985223336494743), please take a look at the output screen below.

enter image description here

The value of Z = (857). Please take a look at the output screen below.

enter image description here

0
source

All Articles