Division and remainder of large numbers in JavaScript

Viewed 4346

I'm trying to get the remainder of a large number, for example:

1551690021432628813 % 64

But I find that the it's a couple of digits too long for JavaScript. i.e. it's getting rounded to zero.

Is there a way around this other than using a 26kb library like BigInteger.js?

6 Answers

thank you John Coleman

javascript version :

    function calculateMod(str, mod) {
        var n = str.length;
        if (n <= 10) {
            return parseInt(str) % mod;
        }
        else {
            var first = str.substring(0, n - 10)
            var second = str.substring(n - 10)
            return (calculateMod(first, mod) * (Math.pow(10, 10) % mod) + parseInt(second) % mod) % mod;
        }
    }

// you can use the built-in BigInt object
console.log(Number(1551690021432628813n % 64n));

BigInt(1551690021432628813) % 64

Related