The problem
In arithmetic, the factorial of a non-negative integer n, denoted by n!, is the product of all constructive integers lower than or equal to n. For instance: 5! = 5 * 4 * 3 * 2 * 1 = 120. By conference the worth of 0! is 1.
Write a perform to calculate factorial for a given enter. If enter is under 0 or above 12 return -1
(C).
The answer in C
Possibility 1:
int factorial(int n) {
if(n<0 ||n>12)
return -1;
if(n==0) {
return 1;
} else {
return n*factorial(n-1);
}
}
Possibility 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];
}
Possibility 3:
int factorial(int n) {
if (n < 0 || n > 12)
return -1;
int consequence = 1;
for (int i = n; i > 1; i--) {
consequence *= i;
}
return consequence;
}
Take a look at circumstances to validate our resolution
#embrace <criterion/criterion.h>
int factorial(int n);
Take a look at(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 two is 2");
cr_assert_eq(factorial(3), 6, "factorial for 3 is 6");
}