QUESTION 21 · Worked algorithms
Define factorial and state the values of 0! and 5!.
2 marksAnswer
For a non-negative integer n, n! is the product from 1 through n; 0! is defined as 1.
- 0! = 1.
- 5! = 5 × 4 × 3 × 2 × 1 = 120.
QUESTION 21 · Worked algorithms
For a non-negative integer n, n! is the product from 1 through n; 0! is defined as 1.
QUESTION 22 · Worked algorithms
The factorial of a non-negative integer n is the product of the integers from 1 to n. It is written as n!. By definition, 0! = 1.
For n = 5, the product starts at 1. Multiplying by 2 gives 2; multiplying by 3 gives 6; multiplying by 4 gives 24; multiplying by 5 gives 120. Thus 5! = 120. Each loop step adds one required factor to the product.
The product must start at 1, not 0. A product that starts at zero stays zero after every multiplication. When n is 0 or 1, the loop is not entered and the answer remains 1. Negative inputs are rejected because they are outside this elementary factorial definition.
Factorials grow quickly. The example accepts only 0 through 20 and uses unsigned long long. This type has enough guaranteed range for 20!, but not for every factorial. A larger input needs an overflow check or a different way to store large numbers.
The repeated multiplication takes O(n) time in the usual analysis, because the number of loop steps grows with n. Only a few variables are used, so extra space is O(1). The supplied fixed-width program restricts the input to avoid overflow.
/* CodeBhavya | PPS AR25 | Learning example */
#include <stdio.h>
int main(void)
{
int n;
unsigned long long factorial = 1;
if (scanf("%d", &n) != 1 || n < 0 || n > 20) {
puts("Unsupported input");
return 1;
}
for (int i = 2; i <= n; ++i) {
factorial *= (unsigned long long)i;
}
printf("%d! = %llu\n", n, factorial);
return 0;
}55! = 120