Search code examples
javascriptmathmodulopowinfinity

Modulo % with big number- Infinity error - Javascript


Is there are trick to get the modulo of big numbers in Javascript. I am getting 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;
}

Solution

  • There's a mathematical "trick" you can use, if you can assume all parameters are integers.

    Consider the following modulo operation:

    (a*x + y) % x

    Obviously, the a*x part can be discarded and the following holds:

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

    With that in mind we can assume the big number is just a*x + y, and we can perform the modulo at any stage, and as often as we like, so, to get the result you want, do this:

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