欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

JS实现两个大数(整数)相乘

时间:2021-11-21 10:51:22|栏目:JavaScript代码|点击:
大数,即超出语言所能表示的数字最大范围的数字,此时的数字只能用字符串来表示。那么如何实现两个大数相乘呢?我用JS实现了一下,代码如下:
复制代码 代码如下:

console.log(bigMut("567", "1234")); // 699678
function bigMut(big, common) {
big += "";
common += "";
if (big.length < common.length) {
big = [common, common = big][0];
}
big = big.split("").reverse();
var oneMutManyRes = [];
var i = 0,
len = big.length;
for (; i < len; i++) {
oneMutManyRes[oneMutManyRes.length] = oneMutMany(big[i], common) + getLenZero(i);
}
var result = oneMutManyRes[0];
for (i = 1, len = oneMutManyRes.length; i < len; i++) {
result = bigNumAdd(result, oneMutManyRes[i]);
}
return result;
}
function getLenZero(len) {
len += 1;
var ary = [];
ary.length = len;
return ary.join("0");
}
function oneMutMany(one, many) {
one += "";
many += "";
if (one.length != 1) {
one = [many, many = one][0];
}
one = parseInt(one, 10);
var i = 0,
len = many.length,
resAry = [],
addTo = 0,
curItem,
curRes,
toSave;
many = many.split("").reverse();
for (; i <= len; i++) {
curItem = parseInt(many[i] || 0, 10);
curRes = curItem * one + addTo;
toSave = curRes % 10;
addTo = (curRes - curRes % 10) / 10;
resAry.unshift(toSave);
}
if (resAry[0] == 0) {
resAry.splice(0, 1);
}
return resAry.join("");
}
function bigNumAdd(big, common) {
big += "";
common += "";
var maxLen = Math.max(big.length, common.length),
bAry = big.split("").reverse(),
cAry = common.split("").reverse(),
i = 0,
addToNext = 0,
resAry = [],
fn,
sn,
sum;
for (; i <= maxLen; i++) {
fn = parseInt(bAry[i] || 0);
sn = parseInt(cAry[i] || 0);
sum = fn + sn + addToNext;
addToNext = (sum - sum % 10) / 10;
resAry.unshift(sum % 10);
}
if (resAry[0] == 0) {
resAry.splice(0, 1);
}
return resAry.join("");
}

上一篇:JavaScript闭包原理与用法实例分析

栏    目:JavaScript代码

下一篇:20行JS代码实现粘贴板复制功能

本文标题:JS实现两个大数(整数)相乘

本文地址:http://www.codeinn.net/misctech/184349.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有