两个超大的数字相乘
这里两个超大的数字相乘,用到前面的两个超大的数字相加的方法,所以这里顺便贴一下代码。
两个超大的数字相加
function largeCount(f, t) { f += ""; t += ""; let fl = f.length, tl = t.length, arr = [], i = 0, spacing = fl - tl, len = 0, lastMan = [], fr = f.split("").reverse(), tr = t.split("").reverse(), current = 0, curr = 0, isT, maxLen; if (spacing > 0) { len = tl; lastMan = fr; maxLen = fl; } else { len = fl; lastMan = tr; maxLen = tl; } function course(current, i) { if (current > 9) { arr[i] = current % 10; arr[i + 1] = 1; return true; } else { arr[i] = current; return false; } } for (; i < len;) { curr = arr[i] ? arr[i] : 0; current = fr[i] * 1 + tr[i] * 1 + curr * 1; course(current, i++); if (i === len) { if (arr[i]) { do { curr = lastMan[i]; if (curr) { current = lastMan[i] * 1 + arr[i] * 1; isT = course(current, i++); } else { isT = false; } } while (isT && i < maxLen); } arr = [...arr, ...lastMan.slice(i)]; } } return arr.reverse().join(""); }
下面是两个超大的数字相乘的代码
两个超大的数字相乘
function multiply(f, t) { let current, currentLevel, i, j, mult, a1, a2, zero; let fl = f.length; let tl = t.length; let result = []; let fArr = []; let tArr = []; let maxLen = fl > tl ? fl : tl; f = reverse(f); t = reverse(t); function reverse(s) { return s.split('').reverse().join(''); } function addZero(n) { let t = ''; for (j = 0; j < n; j++) { t += '0'; } return t; } for (i = 0; i < maxLen; i++) { zero = addZero(i); a1 = f[i]; a2 = t[i]; if (a1) { fArr[i] = [a1, zero]; } if (a2) { tArr[i] = [a2, zero]; } } for (i = 0; i < fl; i++) { current = fArr[i]; for (j = 0; j < tl; j++) { currentLevel = tArr[j]; result.push((current[0] * 1) * (currentLevel[0] * 1) + current[1] + currentLevel[1]); } } maxLen = result.length; mult = result[0]; for (i = 1; i < maxLen; i++) { mult = largeCount(mult, result[i]); } return mult; }
主要的原理,大家看代码应该就能理解,这里就不再赘述。
声明:严禁抄袭,欢迎转载!不过请带上博文链接!
或者你有更好的实现方式、或者你觉得有可以优化的地方,不妨评论讨论下!觉得得到帮助的可以点个推荐,让更多人也可以得到帮助。