Skip to content

Instantly share code, notes, and snippets.

@ggilder
Created April 16, 2012 00:04
Show Gist options
  • Select an option

  • Save ggilder/2395449 to your computer and use it in GitHub Desktop.

Select an option

Save ggilder/2395449 to your computer and use it in GitHub Desktop.
Javascript subtracting from large integers
function LargeInt(str){
this.length = 0;
if (str){
Array.prototype.push.apply(this, String(str).split(''));
}
}
LargeInt.prototype = {
splice: Array.prototype.splice,
minus: function(subtrahend){
subtrahend = new LargeInt(subtrahend);
if (subtrahend.greaterThan(this)){
return "-" + subtrahend._minus(this);
} else {
return this._minus(subtrahend);
}
},
_minus: function(subtrahend){
var difference = [];
for(var i=0,l=this.length; i<l; i++){
var digit = this.digitFromEnd(i);
var subDigit = subtrahend.digitFromEnd(i);
if (digit >= subDigit){
difference[i] = digit - subDigit;
} else {
difference[i] = digit + 10 - subDigit;
subtrahend.setDigitFromEnd(i+1, subtrahend.digitFromEnd(i+1) + 1);
}
}
var result = difference.reverse().join('').replace(/^0+/,'');
if (result === '')
result = '0';
return result;
},
greaterThan: function(compareTo){
if (compareTo.length != this.length) {
return this.length > compareTo.length;
}
for(var i=this.length-1; i>=0; i--){
var x = this.digitFromEnd(i), y = compareTo.digitFromEnd(i);
if (x == y) {
continue;
} else {
return x > y;
}
}
return false;
},
_fromEnd: function(revIndex){
return this.length - 1 - revIndex;
},
digitFromEnd: function(revIndex){
return parseInt(this[this._fromEnd(revIndex)] || 0, 10);
},
setDigitFromEnd: function(revIndex, val){
this[this._fromEnd(revIndex)] = val;
}
};
function subtractFromLargeNumber(num, subtract){
num = new LargeInt(num);
return num.minus(subtract);
}
var testCases = [
{
largeNumber: "199000000000000000",
expected: "198999999999999995",
subtract: 5
},
{
largeNumber: "432467823478368774",
expected: "432467823478368765",
subtract: 9
},
{
largeNumber: "200",
expected: "-101",
subtract: 301
},
{
largeNumber: "4958",
expected: "0",
subtract: "4958"
},
{
largeNumber: "432467823478368774",
expected: "-123205909923154",
subtract: "432591029388291928"
}
];
testCases.forEach(function(test){
var result = subtractFromLargeNumber(test.largeNumber, test.subtract);
if (result != test.expected) {
console.log("fail! expected "+test.expected+", got "+result);
} else {
console.log("success!");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment