Opening the reading…
Opening the reading…
DSA FUNDAMENTALS › MATH BASICS
The factorial of a non-negative integer n is the product of every integer from 1 through n. For the running input n = 5, the notation 5! means 1 * 2 * 3 * 4 * 5, which equals 120. The exclamation mark names the factorial operation, it does not change the final factor or add another multiplication after 5.
5! = 1 * 2 * 3 * 4 * 5
= 120Which expression represents 5!?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
To calculate the product one factor at a time, store the current product in an accumulator. Start result at 1, then multiply it by each factor. Starting at 1 leaves the first multiplication unchanged, because 1 * 1 is 1. Starting at 0 destroys the product immediately, because 0 multiplied by any later factor remains 0.
int n = 5;
int result = 1;
for (int factor = 1; factor <= n; factor++) {
result *= factor;
}Replace result = 0 with the correct accumulator initialization for computing 5!.
int result = 0;Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The factors for 5! are 1, 2, 3, 4, and 5, so the loop starts at 1 and uses the inclusive upper bound factor <= n. This processes factor 5 exactly once. If the loop stops before 5, it computes 1 * 2 * 3 * 4, which is 24. If it continues past 5, it multiplies by an extra factor and no longer computes 5!.
int result = 1;
for (int factor = 1; factor <= 5; factor++) {
result *= factor;
}
// result is 120For n = 5, the loop performs five iterations, one for each factor from 1 through 5. The running time is linear in n because the loop processes each factor once. The program stores only the accumulator and the loop variable, so its extra space is constant, written as O(1).
Factorial values grow quickly, and a fixed-width integer type can overflow when the allowed input becomes larger. Overflow can replace the intended product with an incorrect value, so the input constraints must determine which numeric type is safe. The loop idea stays the same, but the type must be able to hold the final factorial.