-
-
Save popomore/2926355 to your computer and use it in GitHub Desktop.
large number modulus fix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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