简体   繁体   中英

How to calculate division remainder of 64bit integer given as string in Javascript

Is there fast and simple way to make an "%" operation for 64bit integer given as "string" (for example "1bed658e4cbba3a7")?

I know that Google Closure Library has such function, but I'd prefer not to use any external libraries, and moreover internally it works as three operations (division, multiplication and substraction) and seems to be not optimal.

Added : Problem is that JavaScript cannot handle 64bit integers without loosing precision. For details see this question

If you have an upper bound on the right-hand operand, then you can split the 64-bit int into two parts, and calculate the modulus from that. (It's three % operations, and I don't know whether that's fast enough for your purposes).

For example, if you want to calculate x % c, and c < 2^32, then you can split x into two parts, a and b, and calculate:

(a * 2^32 + b) % c = (((a % c)* (2^32 % c)) + b) % c

This depends on c being small, though. If it is also close to 64 bits, then you will want to look for other methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM