js实现大数
大数相加的实现
在JavaScript中处理大数相加时,由于Number类型有精度限制(最大安全整数为2^53 - 1),直接相加可能导致精度丢失。以下是两种常见解决方案:
方法一:字符串模拟竖式加法
function addBigNumbers(a, b) {
let i = a.length - 1;
let j = b.length - 1;
let carry = 0;
let result = '';
while (i >= 0 || j >= 0 || carry > 0) {
const digitA = i >= 0 ? parseInt(a[i--]) : 0;
const digitB = j >= 0 ? parseInt(b[j--]) : 0;
const sum = digitA + digitB + carry;
result = (sum % 10) + result;
carry = Math.floor(sum / 10);
}
return result;
}
方法二:使用BigInt类型(ES2020+)
function addBigNumbers(a, b) {
return (BigInt(a) + BigInt(b)).toString();
}
大数相乘的实现
大数相乘同样需要考虑精度问题:
字符串模拟竖式乘法
function multiplyBigNumbers(a, b) {
if (a === '0' || b === '0') return '0';
const m = a.length, n = b.length;
const result = new Array(m + n).fill(0);
for (let i = m - 1; i >= 0; i--) {
for (let j = n - 1; j >= 0; j--) {
const product = (a[i] - '0') * (b[j] - '0');
const sum = result[i + j + 1] + product;
result[i + j + 1] = sum % 10;
result[i + j] += Math.floor(sum / 10);
}
}
return result.join('').replace(/^0+/, '');
}
大数阶乘计算
计算大数阶乘时需要处理不断增长的数字:

function factorialBigNumber(n) {
let result = '1';
for (let i = 2; i <= n; i++) {
let carry = 0;
const temp = [];
for (let j = result.length - 1; j >= 0; j--) {
const product = (result[j] - '0') * i + carry;
temp.unshift(product % 10);
carry = Math.floor(product / 10);
}
while (carry > 0) {
temp.unshift(carry % 10);
carry = Math.floor(carry / 10);
}
result = temp.join('');
}
return result;
}
注意事项
- 字符串方法适用于所有JavaScript环境,但实现较复杂
- BigInt类型是现代浏览器和Node.js中的最佳选择(需环境支持)
- 处理超大数字时,字符串方法可能性能较低
- 实际项目中推荐使用第三方库如bignumber.js或decimal.js
以上方法根据具体需求选择,现代开发中优先考虑BigInt方案,兼容性要求高的场景可使用字符串模拟方法。






