JavaScript中的除法和余数 [英] Division and remainder of large numbers in JavaScript

查看:199
本文介绍了JavaScript中的除法和余数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取大量的余数,例如:

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中的除法和余数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆