community wiki - 1 year ago 84
Javascript Question

# 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;
return z;
}
``````

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));``````

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download