Skip to content

Instantly share code, notes, and snippets.

@d3x0r
Last active June 6, 2017 06:49
Show Gist options
  • Save d3x0r/eef107e3220a60fda16a36b1b964459b to your computer and use it in GitHub Desktop.
Save d3x0r/eef107e3220a60fda16a36b1b964459b 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/100000)|0;
result.push(op%100000);
}
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/100000)|0;
result.push( op%100000 );
}
if(carry) result.push( carry );
return result;
}
function intToArray(i) {
var tmp = i.toString().split('').reverse().map( (a)=>parseInt(a) );
var tmp2 = [];
var parts = (((tmp.length+4)/5)|0) - 1;
var last = tmp.length % 5;
for( var n = 0; n < parts; n++ ) {
tmp2.push( tmp[n*5+0] * 1 + tmp[n*5+1] * 10 + tmp[n*5+2] * 100 + tmp[n*5+3] * 1000 + tmp[n*5+4] * 10000 );
}
if( last == 0 )
tmp2.push( tmp[n*5+0] * 1 + tmp[n*5+1] * 10 + tmp[n*5+2] * 100 + tmp[n*5+3] * 1000 + tmp[n*5+4] * 10000 );
else if( last == 4 )
tmp2.push( tmp[n*5+0] * 1 + tmp[n*5+1] * 10 + tmp[n*5+2] * 100 + tmp[n*5+3] * 1000 );
else if( last == 3 )
tmp2.push( tmp[n*5+0] * 1 + tmp[n*5+1] * 10 + tmp[n*5+2] * 100 );
else if( last == 2 )
tmp2.push( tmp[n*5+0] * 1 + tmp[n*5+1] * 10 );
else
tmp2.push( tmp[n*5+0] * 1 );
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(10);
if( i ) for( var n = s.length; n < 5; 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