How to Fix for Factorial in C

The obstacle

In mathematics, the factorial of a non-negative integer n, signified by n!, is the item of all favorable integers less than or equivalent to n. For instance: 5! = 5 * 4 * 3 * 2 * 1 = 120. By convention the worth of 0! is 1.

Compose a function to compute factorial for a provided input. If input is listed below 0 or above 12 return -1 ( C).

The option in C

Choice 1:

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

Choice 2:

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

Choice 3:

 int factorial( int n) {

if (n < < 0|| n > > 12).
return -1;.

int outcome = 1;.
for (int i = n; i > > 1; i--) {
outcome *= i;.
}

return outcome;.

}

Test cases to verify our option

 #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");.
}

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: