问题描述
作为一个实验,我使用BigInt
在JavaScript中计算了60000!
(阶乘).大约花了3.8秒.为了显示结果的某些(或任何)表示形式,我只是使用
As an experiment, I calculated 60000!
(factorial) in JavaScript using BigInt
. It took about 3.8 seconds. To show some (or any) representation of the result, I just showed the first 10 digits on screen, using
result.toString().slice(0, 10)
但令我惊讶的是,此操作花费了将近4秒钟,并且阻止了浏览器(Google Chrome)的所有用户界面. (我确实有某种机制可以在阶乘的计算过程中产生处理器时间,因此不会阻塞UI).
But to my surprise, this operation took close to 4 seconds and is blocking all UI of the browser (Google Chrome). (I did have some mechanism to yield processor time during the calculation of the factorial, so that wasn't blocking the UI).
有什么方法可以快速显示此数字?
Is there some way to show a representation of this number fast?
其他信息:result.toString().length
是260630
.如果此数字显示在页面上,它将不会换行到下一行,并且Chrome标签可能会冻结,因为它试图创建宽度适合该数字的页面.
Additional info: result.toString().length
is 260630
. If this number was shown on the page, it won't wrap to the next line, and the Chrome tab might freeze, as it was trying to create a page with the width suitable to fit in this number.
推荐答案
该数字(或仅其前10位数字)的输出花费那么多时间的主要原因是该数字必须转换为十进制表示形式.这是一个巨大的计算,涉及数以千计的字节的移位,大数的减法,通过多个字节的龋齿以及所有重复的数千次.
The main reason why the output of the number (or only its first 10 digits) takes that much time is that the number must be converted to a decimal representation. This is a huge calculation, involving shifts of many thousands of bytes, subtractions of big numbers, with a cary passing through that many bytes, and all that repeated thousands of times.
如果将输出代码替换为:
If you replace the outputting code with:
result.toString(2).slice(0, 10)
// ^^
...您会发现速度有了极大的提高.原因是此操作不需要基本转换,并且可以线性时间(以字节数为单位)构建字符串.
... you'll see a drastic improvement in speed. The reason is that for this operation no base conversion is needed, and the string can be built in linear time (in terms of the number of bytes).
这篇关于JavaScript中是否有一种方法可以在相对较快的时间内获得很大数量的BigInt类型的表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!