Skip to content

Instantly share code, notes, and snippets.

@d3x0r
Created June 6, 2017 06:59
Show Gist options
  • Save d3x0r/061c7665426d8c7492a086169fd78b90 to your computer and use it in GitHub Desktop.
Save d3x0r/061c7665426d8c7492a086169fd78b90 to your computer and use it in GitHub Desktop.
"use asm";
(function(){
function multiplyStrings(a,b){
var result = [];
var dummy = [];
for(var i=0; i < b.length; i++) {
if( i ) dummy.push(0);
var dummy2 = multiplyWithOneDigit(a,b[i], dummy.slice());
result = addToStringumbers(result,dummy2);
}
return result;
}
function multiplyWithOneDigit(a,b,base){
var result = base;
var carry = 0;
for(var i=0; i < a.length; i++) {
var op = a[i]*b+carry;
carry = (op >> 16);
result.push(op&0xFFFF);
}
if( carry ) result.push(carry);
return result;
}
function addToStringumbers(a,b){
if(a.length == 0)
return b;
var carry = 0;
var result = [];
for(var i=0; i < b.length; i++){
if( i >= a.length )
var op = b[i]+carry;
else
var op = a[i]+b[i]+carry;
carry = (op>>16);
result.push( op&0xFFFF );
}
if(carry) result.push( carry );
return result;
}
function intToArray(i) {
if( i < 65536 )
return [parseInt(i)];
else
return [parseInt(i) & 0xFFFF, parseInt(i) >> 16];
return tmp2;
}
function factorial(x){
var result = [1];
for(var i=2; i<=x; i++){
result = multiplyStrings(result, intToArray(i));
}
var tmp = result.reverse();
var tmp2 = tmp.map( (n,i)=>{
var s = n.toString(16);
if( i ) for( var n = s.length; n < 4; n++ ) s = "0" + s;
return s } );
return tmp2.join("");
}
var now = Date.now();
console.log(factorial(process.argv[2]));
console.log( "del:", Date.now() - now );
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment