js 除数和余数,JavaScript中的除数和余数

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?

解决方案

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

Hence

1551690021432628813 % 64 = (155169002 % 64 * (10**10) % 64 + 1432628813 % 64) % 64

(Which equals 13).

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

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

For example,

1551690021432628813 % 64 = 628813 % 64 = 13

Similar remarks hold whenever the modulus is a power of 2.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值