Skip to content

Instantly share code, notes, and snippets.

@vdakalov
Created December 19, 2017 05:30
Show Gist options
  • Save vdakalov/da47c98ae3151cc86660876372888b9a to your computer and use it in GitHub Desktop.
Save vdakalov/da47c98ae3151cc86660876372888b9a to your computer and use it in GitHub Desktop.
Алгоритм вычитания очень больших чисел на JavaScript
#!/usr/bin/env node
function sub(a, b) {
let prefix = '0'.repeat(Math.abs(a.length - b.length));
let flip = false;
if (prefix.length) {
if (a.length > b.length) {
b = `${prefix}${b}`;
} else if (b.length > a.length) {
a = `${prefix}${a}`;
// flipped
a = [b, b = a][0];
flip = true;
}
}
const r_buffer = [];
for (let i = a.length - 1; i >= 0; i--) {
r_buffer[i] = parseInt(a[i]) - parseInt(b[i]);
}
for (let i = r_buffer.length - 1; i > 0; i--) {
if (0 > r_buffer[i]) {
r_buffer[i] = 10 + r_buffer[i];
r_buffer[i - 1] = r_buffer[i - 1] - 1;
}
}
while (r_buffer[0] === 0) {
r_buffer.shift();
}
let c = r_buffer.length ? r_buffer.join('') : '0';
return flip ? -c : c;
}
const a = '80';
const b = '90';
console.log(sub(a, b));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment