How to Solve for Factorial in C


The challenge

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example: 5! = 5 * 4 * 3 * 2 * 1 = 120. By convention the value of 0! is 1.

Write a function to calculate factorial for a given input. If input is below 0 or above 12 return -1 (C).

The solution in C

Option 1:

int factorial(int n) {
    if(n<0 ||n>12)
      return -1;
    if(n==0) {
      return 1;
    } else {
      return n*factorial(n-1);
    }
}

Option 2:

int factorial(int n)  {
  static int F[] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600};
  return n < 0 || n > 12 ? -1 : F[n];
}

Option 3:

int factorial(int n) {

    if (n < 0 || n > 12)
      return -1;
    
    int result = 1;
    for (int i = n; i > 1; i--) {
      result *= i;
    }
    
    return result;

}

Test cases to validate our solution

#include <criterion/criterion.h>

int factorial(int n);

Test(Example_Tests, should_pass_all_the_tests_provided)
{
    cr_assert_eq(factorial(1), 1, "factorial for 1 is 1");
    cr_assert_eq(factorial(2), 2, "factorial for 2 is 2");
    cr_assert_eq(factorial(3), 6, "factorial for 3 is 6");
}