Databases Reference
In-Depth Information
3.
Create the function FACTORIAL_ITERATIVE to calculate the factorial of a given
number using an iterative algorithm:
CREATE OR REPLACE FUNCTION FACTORIAL_ITERATIVE (ANUM NUMBER)
RETURN NUMBER IS
AVALUE NUMBER := 1;
BEGIN
FOR J IN 2..ANUM LOOP
AVALUE := AVALUE * J;
END LOOP;
RETURN AVALUE;
END;
4.
Compare the execution speed of the functions, while calculating the factorial of a
big number:
SET TIMING ON
SELECT FACTORIAL_RECURSIVE(1000000) FROM DUAL;
SELECT FACTORIAL_ITERATIVE(1000000) FROM DUAL;
SET TIMING OFF
5.
Drop the functions created in this recipe:
DROP FUNCTION FACTORIAL_RECURSIVE;
DROP FUNCTION FACTORIAL_ITERATIVE;
How it works...
In step 2, we created a function to calculate the factorial of a number—denoted by n! in
mathematics—using a recursive function, that is, a function that calls itself to calculate
the result.
In step 3, we implement the same function, using an iterative algorithm to calculate the
same value.
In step 4, we execute these two functions with the same number to verify the speed of the
two implementations. The result of the execution is as follows:
 
Search WWH ::




Custom Search