Skip to content

Instantly share code, notes, and snippets.

@d3x0r
Created June 6, 2017 07:42
Show Gist options
  • Save d3x0r/7aad1ecca37956dfdc6d6a054122f1d8 to your computer and use it in GitHub Desktop.
Save d3x0r/7aad1ecca37956dfdc6d6a054122f1d8 to your computer and use it in GitHub Desktop.
(function(){
function multiplyStrings(a,b){
var result = [];
for(var i=0; i < b.length; i++) {
result = addToStringumbers(result,multiplyWithOneDigit(a,b[i]));
}
return result;
}
function multiplyWithOneDigit(a,b){
var result = new Array(a.length);
var carry = 0;
for(var i=0; i < a.length; i++) {
var op = a[i]*b+carry;
carry = (op/100000)|0;
result[i] = (op%100000);
}
if( carry ) result.push(carry);
return result;
}
function addToStringumbers(a,b){
if(a.length == 0)
return b;
var carry = 0;
var result = new Array(b.length);
for(var i=0; i < a.length; i++){
var op = a[i]+b[i]+carry;
carry = (op/100000)|0;
result[i] = ( op%100000 );
}
for( ; i < b.length; i++){
var op = b[i]+carry;
carry = (op/100000)|0;
result[i] = ( op%100000 );
}
if(carry) result.push( carry );
return result;
}
function intToArray(i) {
//if( i < 100000 )
return [i];
//else
// return [i %100000, i / 100000]
}
function factorial(x){
var result = [1];
var thisNum = [0];
for(var i=2; i<=x; i++){
thisNum[0] = i;
//result = addToStringumbers(result,multiplyWithOneDigit(result,i));
result = multiplyStrings(result,thisNum);// 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