• If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • Dokkio Sidebar (from the makers of PBworks) is a Chrome extension that eliminates the need for endless browser tabs. You can search all your online stuff without any extra effort. And Sidebar was #1 on Product Hunt! Check out what people are saying by clicking here.



Page history last edited by Kenneth Finnegan 14 years, 3 months ago

Calculating factorials is one of the most classic examples used in teaching recursion.  The code to do so is quite simple:

int factorial(int i) {


          return i * factorial(i-1);

     return 1;



The realistic problem with this is that factorials get really big, really fast.  Only 13! is so large that it overflows a 32 bit int.  Unless you're dealing with 64 bit numbers, it makes more sense to use a lookup table.  The work just isn't worth it.



int factorial(int i) {

     if (i<0 || i>12) {

          fprintf(stderr, "Factorial input out of range\n");

          exit(EXIT_FAILURE); // You could also return an error code like -1


     static const int factorials[] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600};

     return factorials[i];



If you need larger factorials, use a 64 bit number (long long or int64_t).  You could still use a lookup table for improved performance.



I can't remember where I read this trick.

Comments (0)

You don't have permission to comment on this page.