Created
November 6, 2016 14:51
-
-
Save vojty/a94104a4cb3eb7ff36584de96fb9a4cc to your computer and use it in GitHub Desktop.
Large numbers multiplication
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
function mul(num1, num2) { | |
// Convert to array of string in reverse order (right to left calc) | |
num1 = `${num1}`.split('').reverse(); | |
num2 = `${num2}`.split('').reverse(); | |
// Init empty array | |
const d = []; | |
for(let i = 0; i < num1.length + num2.length; i++) { | |
d[i] = 0; | |
} | |
// Calculate each digits | |
for (let i = 0; i < num1.length; i++) { | |
for (let j = 0; j < num2.length; j++) { | |
d[i + j] += parseInt(num1[i]) * parseInt(num2[j]); | |
} | |
} | |
const numbers = []; | |
for(let i = 0; i < d.length; i++){ | |
const number = d[i] % 10; | |
const carry = Math.floor(d[i] / 10); | |
if (i + 1 < d.length){ | |
d[i + 1] += carry; | |
} | |
numbers.push(number); | |
} | |
return numbers.reverse().join('').replace(/^0*/, ''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment