A blog on Computer Science, Security, Programming, and more...

HeapSpray Blog » Programming » View Post


Factorials Without Recursion or Loops

Written by Matt

I never see this exemplified in any demonstrations of how to compute a factorial, but you can compute a factorial by computing e raised to the natural logarithm of the gamma function (which is an extension of the factorial to the real and complex numbers).

Mathematically it looks as follows:

(1) eln(Γ(n+1))

where e is Euler's Number, n is the argument you would give to the factorial function, and Γ is the gamma function.

The Standard C Math Library has all of these functions, and the log-gamma factorial can be implemented in C/C++ in one line as follows:

long int fac(unsigned long int n) {
  return lround(exp(lgamma(n+1)));

lround() is used just because exp() returns a float, and exp raises e to its argument's power. Make sure to include math.h or cmath for C and C++ respectively.

  • Name and Email fields are optional
  • Your email will not be public, only the administrator can see it
  • You are rate limited to one comment for every 10 minutes