大数相乘

来源:互联网 发布:淘宝卖家账户被监管 编辑:程序博客网 时间:2024/06/09 15:02
/*    有两个用字符串表示的非常大的大整数,算出他们的乘积,也是用字符串表示。不能用系统自带的大整数类型。 */var s1='72106547548473106236',    s2='982161082972751393';// 字符串转为数组n1=s1.split('');n2=s2.split('');// 将数组每一项转为整数n1.forEach(function (t,i) { n1[i]=parseInt(t); });n2.forEach(function (t,i) { n2[i]=parseInt(t); });var res=[];var tempRes=[];// 将n2的每一项与n1的每一项相乘for(var i=n2.length-1;i>=0;i--){    var curIncrement=0,nextIncrement; // curIncrement当前需要额外加上的进位,nextIncrement当前需要向下进的位    tempRes=[];    var k=n2.length-1-i;    while (k--){      tempRes.push(0);    }    for(var j=n1.length-1;j>=0;j--){        var prod=n2[i]*n1[j]+curIncrement;        nextIncrement=prod<10?0:Math.floor(prod/10);        curIncrement=nextIncrement;        if(j===0&&nextIncrement!==0){            // 潜在的问题: unshift效率低下            tempRes.unshift(Math.floor(prod%10));            tempRes.unshift(Math.floor(nextIncrement));        }else{            tempRes.unshift(Math.floor(prod%10));        }    }    res=arrPlus(res,tempRes);}// 将两个数组在对应位上相加 arrPlus([8,7,0,1],[9,9,2,3,4,0]=[1,0,0,1,0,4,1]function arrPlus(arr1,arr2) {    var p1=arr1.length,        p2=arr2.length;    var arrLonger=p1>p2?arr1:arr2;    var arrShorter=p1>p2?arr2:arr1;    // 将短的数组高位补0    var t=arrLonger.length-arrShorter.length;    while (t--){        arrShorter.unshift(0);    }    var curIncrement=0,nextIncrement;    for(var i=arrLonger.length-1;i>=0;i--){        var sum=arrLonger[i]+arrShorter[i]+curIncrement;        nextIncrement=sum<10?0:Math.floor(sum/10);        curIncrement=nextIncrement;        if(i===0&&nextIncrement!==0){            arrLonger[i]=Math.floor(sum%10);            arrLonger.unshift(nextIncrement);        }else{            arrLonger[i]=Math.floor(sum%10);        }    }    return arrLonger; }console.log(res.join('')); // 70820244829634538040848656466105986748