Skip to content

Instantly share code, notes, and snippets.

@hanikesn
Created January 18, 2016 01:47
Show Gist options
  • Save hanikesn/a41a88a8e41159a2901b to your computer and use it in GitHub Desktop.
Save hanikesn/a41a88a8e41159a2901b to your computer and use it in GitHub Desktop.
JavaScript BigNum
function reverse(s){
return s.split("").reverse().join("");
}
function add(left, right) {
if(left.length < right.length) {
var swp = left;
left = right;
right = swp;
}
rleft = reverse(left);
rright = reverse(right);
var result = "";
var uebertrag = 0;
for(var i = 0; i < rleft.length; i++) {
var tmp = Number(rleft[i]) + Number(rright[i] === undefined ? "0" : rright[i]);
tmp += uebertrag;
uebertrag = Math.floor(tmp / 10);
result += "" + (tmp % 10);
}
if(uebertrag == 1) {
return "1" + reverse(result);
}
return reverse(result);
}
function multiplyDigit(num, digit) {
var rnum = reverse(num);
var result = "";
var uebertrag = 0;
for(var i = 0; i < rnum.length; i++) {
var tmp = rnum[i] * digit + uebertrag;
result += "" + (tmp % 10);
uebertrag = Math.floor(tmp / 10);
}
if(uebertrag > 0) {
return "" + uebertrag + reverse(result);
}
return reverse(result);
}
function multiply(left, right) {
if(left.length > right.length) {
var swp = left;
left = right;
right = swp;
}
var rleft = reverse(left);
var result = "";
var wertigkeit = "";
for(var i = 0; i < rleft.length; i++) {
var tmp = multiplyDigit(right, Number(rleft[i])) + wertigkeit;
result = add(tmp, result);
wertigkeit += "0";
}
return result;
}
function benchmark(num) {
var startTime = window.performance.now();
multiply(num, num);
var endTime = window.performance.now();
console.log(num.length, endTime - startTime);
}
benchmark("0");
benchmark("12390128930");
benchmark("1239012893012390128930");
benchmark("12390128930123901289301239012893012390128930");
benchmark("1239012893012390128930123901289301239012893012390128930123901289301239012893012390128930");
benchmark("12390128930123901289301239012893012390128930123901289301239012893012390128930123901289301239012893012390128930123901289301239012893012390128930123901289301239012893012390128930");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment