Search code examples
language-agnosticgmpfactorial

Can one know how large a factorial would be before calculating it?


I'm using GMP to calculate very large factorials (e.g. 234234!). Is there any way of knowing, before one does the calculation, how many digits long the result will (or might) be?


Solution

  • The logarithm of the factorial can be used to calculate the number of digits that the factorial number will take:

    logn!

    This can be easily translated to an algorithmic form:

    //Pseudo-code
    function factorialDigits (n) 
      var result = 0;
    
      for(i = 1; i<=n; i++)
        result += log10(n);
    
      return result;