Factorial
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.
For example,
Calculators? How long it will take?
Solution: We can use Computer Programming Language to find the factorial value within Nano Seconds. And here is the PL/SQL Program to find out the factorial values for 10 positive integers.
PL/SQL
Procedure
SQL> CREATE OR REPLACE FUNCTION Factorial(fact INTEGER)
2 RETURN NUMBER AS
3 BEGIN
4 IF fact = 1 THEN
5 RETURN 1;
6 ELSE
7 RETURN(fact * Factorial(fact-1));
8 END IF;
9 END;
10 /
Function created.
SQL> DECLARE
2 n NUMBER := 10;
3 i INTEGER ;
4 BEGIN
5 FOR i IN 1..n LOOP
6 DBMS_OUTPUT.PUT_LINE('The factorial of' ||
7 i || 'is' || Factorial(fact));
8 END LOOP;
9 END;
10 /
2 RETURN NUMBER AS
3 BEGIN
4 IF fact = 1 THEN
5 RETURN 1;
6 ELSE
7 RETURN(fact * Factorial(fact-1));
8 END IF;
9 END;
10 /
Function created.
SQL> DECLARE
2 n NUMBER := 10;
3 i INTEGER ;
4 BEGIN
5 FOR i IN 1..n LOOP
6 DBMS_OUTPUT.PUT_LINE('The factorial of' ||
7 i || 'is' || Factorial(fact));
8 END LOOP;
9 END;
10 /
Output
The factorial of 1 is 1
The factorial of 2 is 2
The factorial of 3 is 6
The factorial of 4 is 24
The factorial of 5 is 120
The factorial of 6 is 720
The factorial of 7 is 5040
The factorial of 8 is 40320
The factorial of 9 is 362880
The factorial of 10 is 3628800
PL/SQL procedure successfully completed.
The factorial of 2 is 2
The factorial of 3 is 6
The factorial of 4 is 24
The factorial of 5 is 120
The factorial of 6 is 720
The factorial of 7 is 5040
The factorial of 8 is 40320
The factorial of 9 is 362880
The factorial of 10 is 3628800
PL/SQL procedure successfully completed.
I used function here. You can also try without function.
SQL> DECLARE
1 i NUMBER;
2 fact NUMBER:=1;
3 n NUMBER;
4 BEGIN
5 n:=&n;
6 FOR i IN 1..n
7 LOOP
8 fact:=fact*i;
9 END LOOP;
10 DBMS_OUTPUT.ENABLE;
11 DBMS_OUTPUT.PUT_LINE('The factorial value of' ||
n|| 'is' ||fact);
12 END;
13 /
1 i NUMBER;
2 fact NUMBER:=1;
3 n NUMBER;
4 BEGIN
5 n:=&n;
6 FOR i IN 1..n
7 LOOP
8 fact:=fact*i;
9 END LOOP;
10 DBMS_OUTPUT.ENABLE;
11 DBMS_OUTPUT.PUT_LINE('The factorial value of' ||
n|| 'is' ||fact);
12 END;
13 /
output wrong...
ReplyDeleteI'm Sorry. I will change it.
Delete