Calculate the factorial of 5
An important mathematical operation is calculating the factorial of a positive integer n. The factorial of n is defined by the product of all positive integers less than or equal to n. For example, the factorial of 3 (denoted by n!) is defined as:
3! = 1 x 2 x 3 = 6
To calculate the factorial of n, many different solutions exist. In this exercise, you will determine the factorial of 5 iteratively with SQL. You can use DECLARE @local_variable to define variables in SQL Server.
Recall the syntax of a WHILE loop is:
WHILE condition
BEGIN
{...statements...}
END;
Diese Übung ist Teil des Kurses
Hierarchical and Recursive Queries in SQL Server
Anleitung zur Übung
- Set the
@targetfactorial, which will also serve as the termination condition, to 5. - Initialize the
@factorialresult. - Calculate the
@factorialnumber by taking the product of the factorial result so far and the current iteration. - Reduce the termination condition by 1 at the end of the iteration.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
-- Define the target factorial number
DECLARE @target float = ___
-- Initialization of the factorial result
DECLARE @factorial float = ___
WHILE @target > 0
BEGIN
-- Calculate the factorial number
SET @factorial = @___ * @___
-- Reduce the termination condition
SET @target = @___ - 1
END
SELECT @factorial;