Since there is a limited number of factorials that can fit into an integer, you can simply pre-calculate the first 20 values โโmanually and save them in a global or static array. Then use a global or static function to find the factorial in the array:
#include <iostream> const int factorials[] = { 1, 1, 2, 6, 24, // etc... }; inline const int factorial(int n) {return factorials[n];} int main() { static const int fourFactorial = factorial(4); std::cout << "4! = " << fourFactorial << "\n"; }
If you use a literal as an argument for factorial , then the compiler should simply replace the function call with the result (when optimization is turned on). I tried the above example in Xcode 4.4 (on Mac), and I see in the assembly that it initializes fourFactorial constant 24:
.loc 1 20 38
This method can lead to faster compilation than using recursive compilation tricks.
source share