Search code examples
javascriptnode.jsfactorial

Node.js output formatting of big numbers


I'm trying to write factorial implementation on node.js. From very simple recursive approach to most complex algorithms. Here is the code:

process.stdin.resume();

var i = 0, t = 0;

process.stdin.on('data', function (n) {
    if (t == 0) {
        t = n;
    } else {
        if (i++ < t) {
            process.stdout.write(Factorial(n).toString());
            if (i == t) {
                process.exit();
            }
        } else {
            process.exit();
        }
    }
});

function Factorial (n) {
    if (n > 1) {
        n *= Factorial(n - 1);
    }
    return n;
}

The problem is — the numbers representation. I expect to have precise answer:

100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

but I'm receiving more logical but useless for me at the moment:

100! = 9.33262154439441e+157

I believe binary representation of the factorial is correct, but how I could get 'loose' form of it?


Solution

  • You could use any of these:

    Implementing a function that computes factorials on top of any of these should be pretty straightforward. If you do so, you might want to use memoization to improve the overall performance. Here is a basic implementation without big integer support:

    var MEMOIZED_FACT = [];
    
    function FACT(number) {
      var n = Math.floor(number);
      if (n === 0 || n === 1) {
        return 1;
      } else if(MEMOIZED_FACT[n] > 0) {
        return MEMOIZED_FACT[n];
      } else {
        return MEMOIZED_FACT = FACT(n - 1) * n;
      }
    }