factorial loop Algorithm
The factorial loop algorithm is a simple and efficient method used to calculate the factorial of a given non-negative integer. Factorial, denoted by n! (where n is a non-negative integer), is the product of all positive integers less than or equal to n. For example, the factorial of 5 (5!) is 5 × 4 × 3 × 2 × 1, which equals 120. The algorithm employs a loop to iterate through the integer values from 1 to n, successively multiplying the loop variable with an accumulator variable that holds the product of the previously computed integer values. The final value of the accumulator variable, after the loop has completed, is the factorial of the input integer.
To implement the factorial loop algorithm, one can use various programming languages, and the general structure of the code remains the same. First, initialize an accumulator variable with a value of 1. Then, create a loop that starts with a loop variable equal to 1 and iterates until the loop variable is equal to the input integer, incrementing the loop variable by 1 at each iteration. Inside the loop, update the accumulator variable by multiplying it with the loop variable. Once the loop is completed, the accumulator variable contains the factorial of the input integer. It is important to note that the factorial of 0 is defined to be 1, which is automatically handled by the algorithm since the accumulator variable is initialized with a value of 1.
long fact_l(int n) {
long out = 1;
for(int i = n; i > 1; i++) {
out *= i;
}
return out;
}