我正在尝试获取大量的余数,例如:
I'm trying to get the remainder of a large number, for example:
1551690021432628813 % 64
但是我发现对于JavaScript来说,它的位数太长了.即将其舍入为零.
But I find that the it's a couple of digits too long for JavaScript. i.e. it's getting rounded to zero.
除了使用像 BigInteger.js 这样的26kb库之外,还有其他方法吗?
Is there a way around this other than using a 26kb library like BigInteger.js?
推荐答案您可以将数字分成10个数字的块(从右侧开始),然后对这些块进行模块化算术,最后将结果合并:
You could break the number into chunks of 10 digits (from the right) and do the modular arithmetic on the chunks, combining the result at the end:
1551690021432628813 = 155169002 * 10**10 + 1432628813因此
1551690021432628813 % 64 = (155169002 % 64 * (10**10) % 64 + 1432628813 % 64) % 64(等于13).
您可以编写实现此思想的递归函数.以下是在Python中使用的语言(我更精通),但应轻松将其翻译成JavaScript:
You could write a recursive function that implements this idea. The following is in Python (which I am more fluent in) but should be easily translated into JavaScript:
def remainder(s,m): #computes int(s) % m, while just using small numbers #s is a string and m is an integer n = len(s) if n <= 10: return int(s) % m else: first = s[:n-10] #first n-10 digits in s second = s[-10:] #last 10 digits return (remainder(first,m) * ((10**10) % m) + int(second) % m) % m对于模数为64的特殊情况,有一种非常简单的方法:64 divides 10**6因此,绝对总是
For the special case that the modulus is 64, there is an exceptionally easy approach: 64 divides 10**6 so, absolutely always
n % 64 == (last 6 digits of n) % 64例如
1551690021432628813 % 64 = 628813 % 64 = 13每当模数为2的幂时,都保持类似的评论.
Similar remarks hold whenever the modulus is a power of 2.
更多推荐
JavaScript中的除法和余数
发布评论