Last active
August 29, 2015 14:27
-
-
Save adamcarr/041987df89ee5a097468 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var chunkSize = 5, batchMod = Math.pow(10, chunkSize); | |
function getChunks(num) { | |
var chunks = [], | |
count = 0; | |
while (true) { | |
var length = chunkSize, | |
shouldBreak = false; | |
var startIndex = num.length - chunkSize * ++count; | |
if (startIndex < 0) { | |
length = chunkSize + startIndex; | |
startIndex = 0; | |
} | |
if (startIndex === 0) shouldBreak = true; | |
chunks.push(parseInt(num.substr(startIndex, length))); | |
if (shouldBreak) break; | |
} | |
return chunks; | |
} | |
function multiply(num1, num2) { | |
var chunks = getChunks(num1), | |
chunks2 = getChunks(num2), | |
products = {}, | |
maxIndex = 0, | |
product = '', | |
carry = 0; | |
for (var i = 0; i < chunks.length; i++) { | |
for (var j = 0; j < chunks2.length; j++) { | |
var productIndex = i + j; | |
if (productIndex > maxIndex) maxIndex = productIndex; | |
products[productIndex] = products[productIndex] || []; | |
products[productIndex].push(chunks[i] * chunks2[j]); | |
} | |
} | |
for (var i = 0; i <= maxIndex; i++) { | |
var sum = products[i].reduce(function(prev, next) { | |
return prev + next; | |
}, carry); | |
var value = (sum % batchMod).toString(); | |
carry = parseInt(sum / batchMod); | |
while (i < maxIndex) { | |
if (value.length < chunkSize) | |
value = '0' + value; | |
else | |
break; | |
} | |
product = value + product; | |
if (i === maxIndex && carry) product = carry + product; | |
} | |
return product; | |
} | |
console.log(multiply('987654', '123456')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment