Skip to content

Instantly share code, notes, and snippets.

@popomore
Created June 13, 2012 20:31
Show Gist options
  • Save popomore/2926355 to your computer and use it in GitHub Desktop.
Save popomore/2926355 to your computer and use it in GitHub Desktop.
large number modulus fix
function mod(dividend, divisor) {
var sDividend = dividend + '';
var split = sDivisor.length + 1;
// if dividend < 9007199254740992 (2^53)
if (sDividend.length < 16) {
return dividend % divisor;
}
// 'abcdefghijklmnopqrstuvwxyz' => ["qrstuvwxyz", "ghijklmnop", "abcdef"]
var l = sDividend.length, s = [];
while (l > 0) {
if (l >= split) {
s.push(sDividend.slice(-split));
sDividend = sDividend.substring(0, sDividend.length - split);
} else {
s.push(sDividend);
}
l -= split;
}
// (a + b) % p = (a % p + b % p) % p
var ret = 0;
for (var i in s) {
var b = s[i], t = Math.pow(10, i * split);
if (!parseInt(b, 10)) continue;
// (a * b) % p = (a % p * b % p) % p
ret += mod(
mod(b, divisor) *
(t === 1 ? 1 : mod(t, divisor)),
divisor
);
}
return mod(ret, divisor);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment