DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Factorial Function

  • submit to reddit
        A (non-recursive) factorial function
int factorial(int x) {
 int fac = 1;
 for (int i=2; i<=x; i++) fac *= i;
 return fac;

Also, with this function defined, you can use two macros for calculating combinations & permutations:
#define nCr(n, r) (factorial(n) / factorial(n-r) / factorial(r))
#define nPr(n, r) (factorial(n) / factorial(n-r))