JavaScript 对大整数求和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4557509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:56:19  来源:igfitidea点击:

JavaScript summing large integers

javascriptbiginteger

提问by Raven

In JavaScript I would like to create the binary hash of a large boolean array (54 elements) with the following method:

在 JavaScript 中,我想使用以下方法创建大型布尔数组(54 个元素)的二进制哈希:

function bhash(arr) {
   for (var i = 0, L = arr.length, sum = 0; i < L; sum += Math.pow(2,i)*arr[i++]); 
   return sum;
}

In short: it creates the smallest integer to store an array of booleans in. Now my problem is that javascript apparently uses floatsas default. The maximum number I have to create is 2^54-1 but once javascript reaches 2^53 it starts doing weird things:

简而言之:它创建了最小的整数来存储布尔数组。现在我的问题是 javascript 显然使用浮点数作为默认值。我必须创建的最大数字是 2^54-1,但是一旦 javascript 达到 2^53,它就会开始做奇怪的事情:

9007199254740992+1 = 9007199254740994

Is there any way of using integers instead of floats in javascript? Or large integer summations?

有没有办法在javascript中使用整数而不是浮点数?还是大整数求和?

采纳答案by martona

JavaScript uses floating point internally.

JavaScript 在内部使用浮点数。

What is JavaScript's highest integer value that a number can go to without losing precision?

一个数字在不损失精度的情况下可以达到的 JavaScript 的最高整数值是多少?

In other words you can't use more than 53 bits. In some implementations you may be limited to 31.

换句话说,您不能使用超过 53 位。在某些实现中,您可能被限制为 31。

Try storing the bits in more than one variable, use a string, or get a bignum library, or if you only need to deal with integers, a biginteger library.

尝试将位存储在多个变量中,使用字符串或获取bignum 库,或者如果您只需要处理整数,则使用biginteger 库

回答by Razor

javascript now has experimental support for BigInt.
At the time of writing only chrome supports this.

javascript 现在BigInt.
在撰写本文时,只有 chrome 支持这一点。

caniusehas no entry yet.

caniuse还没有条目。

BigIntcan be either used with a constructor, e.g. BigInt(20)or by appending n, e.g. 20n

BigInt可以与构造函数一起使用,例如BigInt(20)或通过附加n,例如20n

Example:

例子:

const max = Number.MAX_SAFE_INTEGER;

console.log('javascript Number limit reached', max + 1 === max + 2) // true;

console.log('javascript BigInt limit reached', BigInt(max) + 1n === BigInt(max) + 2n); // false

回答by Mahmoud Khaled

BigIntis being added as a native feature of JavaScript.

BigInt正在作为 JavaScript 的本机功能添加。

typeof 123;
// → 'number'
typeof 123n;
// → 'bigint'

Example:

例子:

const max = BigInt(Number.MAX_SAFE_INTEGER);
const two = 2n;
const result = max + two;
console.log(result);
// → '9007199254740993'

回答by 6502

No. Javascript only has one numeric type. You've to code yourself or use a large integer library (and you cannot even overload arithmetic operators).

不可以。Javascript 只有一种数字类型。您必须自己编写代码或使用大型整数库(您甚至不能重载算术运算符)。

Update

更新

This was true in 2010... now (2019) a BigInt library is being standardized and will most probably soon arrive natively in Javascript and it will be the second numeric type present (there are typed arrays, but - at least formally - values extracted from them are still double-precision floating point numbers).

这在 2010 年是正确的......现在(2019 年)一个 BigInt 库正在被标准化,并且很可能很快就会在 Javascript 中原生出现,它将成为第二个数字类型(有类型化数组,但 - 至少正式 - 提取的值从他们那里仍然是双精度浮点数)。

回答by Alex K

Another implementation of large integer arithmetic (also using BigInt.js) is available at www.javascripter.net/math/calculators/100digitbigintcalculator.htm. Supports the operations + - * / as well as remainder, GCD, LCM, factorial, primality test, next prime, previous prime.

大整数算法的另一种实现(也使用 BigInt.js)可在www.javascripter.net/math/calculators/100digitbigintcalculator.htm 获得。支持运算 + - * / 以及余数、GCD、LCM、阶乘、素性检验、下一个素数、前一个素数。

回答by Abhishek Verma

So while attempting one of the leetcode problem I have written a function which takes two numbers in form of string and returns the sum of those numbers in form of string. (This doesn't work with negative numbers though we can modify this function to cover that)

因此,在尝试其中一个 leetcode 问题时,我编写了一个函数,该函数以字符串的形式接收两个数字,并以字符串的形式返回这些数字的总和。 (这不适用于负数,尽管我们可以修改此函数以覆盖负数)

var addTwoStr = function (s1, s2) {
s1 = s1.split("").reverse().join("")
s2 = s2.split("").reverse().join("")
var carry = 0, rS = '', x = null
if (s1.length > s2.length) {
    for (let i = 0; i < s1.length; i++) {
        let s = s1[i]
        if (i < s2.length) {
            x = Number(s) + Number(s2[i]) + carry
            rS += String((x % 10))
            carry = parseInt(x/10)
        } else {
            if (carry) {
                x = Number(s) + carry
                rS += String((x % 10))
                carry = parseInt(x/10)
            } else {
                rS += s
            }
        }
    }
} else {
    for (let i = 0; i < s2.length; i++) {
        let s = s2[i]
        if (i < s1.length) {
            x = Number(s) + Number(s1[i]) + carry
            rS += String((x % 10))
            carry = parseInt(x/10)
        } else {
            if (carry) {
                x = Number(s) + carry
                rS += String((x % 10))
                carry = parseInt(x/10)
            } else {
                rS += s
            }
        }
    }
}
if (carry) {
    rS += String(carry)
}
return rS.split("").reverse().join("")
}

Example: addTwoStr('120354566', '321442535') Output: "441797101"

示例:addTwoStr('120354566', '321442535') 输出:“441797101”

回答by Stephen C

You're probably running into a byte length limit on your system. I'd take the array of booleans, convert it to an array of binary digits ([true, false, true] => [1,0,1]), then join this array into a string "101", then use parseInt('101',2), and you'll have your answer.

您可能会遇到系统上的字节长度限制。我取布尔数组,将其转换为二进制数字数组 ([true, false, true] => [1,0,1]),然后将此数组加入字符串“101”,然后使用 parseInt ('101',2),你就会得到答案。

回答by YSharp

Here's (yet another) wrapper around Leemon Baird's BigInt.js

这是Leemon Baird 的 BigInt.js(又一个)包装器

It is used in this online demo of a big integer calculator in JavaScriptwhich implements the usual four operations + - * /, the modulus (%), and four builtin functions : the square root (sqrt), the power (pow), the recursive factorial (fact) and a memoizing Fibonacci (fibo).

它用于JavaScript 中的大型整数计算器的在线演示,它实现了通常的四个运算 + - * /、模数 (%) 和四个内置函数:平方根 (sqrt)、幂 (pow)、递归阶乘(事实)和记忆斐波那契数列(fibo)。

回答by z5h

There are various BigInteger Javascript libraries that you can find through googling. e.g. http://www.leemon.com/crypto/BigInt.html

您可以通过谷歌搜索找到各种 BigInteger Javascript 库。例如http://www.leemon.com/crypto/BigInt.html