JavaScript中的除法和余数

编程入门 行业动态 更新时间:2024-10-09 03:23:16
本文介绍了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中的除法和余数

本文发布于:2023-11-29 09:04:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645951.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:余数   除法   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!