Factorial Function

CREATE OR REPLACE FUNCTION factorial(i_val IN PLS_INTEGER)
RETURN PLS_INTEGER AS
BEGIN
IF i_val > 1 THEN
RETURN i_val * factorial(i_val - 1);
ELSE
RETURN 1;
END IF;
END factorial;
/

Factorial Function Testing

SELECT q_tab.i_val "Number", factorial(q_tab.i_val) "Factorial"
FROM (SELECT &i_val as i_val FROM DUAL) q_tab;


Refer SQL Model syntax (Oracle10g and higher) for factorial computation   Factorial - SQL Model

Factorial PL/SQL Block: Using a While Loop

DECLARE
   i_val PLS_INTEGER := &i_val;
   i_fact PLS_INTEGER;
BEGIN
SELECT DECODE(i_val,0,1,i_val) INTO i_fact FROM DUAL;
DBMS_OUTPUT.PUT(' i_val -> '||i_val);
WHILE i_val-1 > 0 LOOP
i_fact := i_fact * (i_val-1);
i_val := i_val -1;
END LOOP;
DBMS_OUTPUT.PUT_LINE(' Factorial -> '||i_fact);
END;
/

Back

Oracle registered trademark of Oracle Corporation.

  1318