Home » SQL & PL/SQL » SQL & PL/SQL » Factorial Function Confusing. (Oracle DB 10.2.0.4.0)
Factorial Function Confusing. [message #677690] 
Mon, 07 October 2019 06:12 
mamalik
Messages: 268 Registered: November 2008 Location: Pakistan

Senior Member 


Dear All,
I saw following code on internet while reading about recursive function. I copied following code and test on my environment. Please see below code.
CREATE OR REPLACE function factorial (
n positive
) return positive
is
begin
if n = 1 then
return n;
else
return N * factorial(n1);
end if;
end;
/
Then i run following statement and got correct result.
Select Factorial(4) from dual;
Confusion is that in function it is written that "If n = 1 then return n". But when i will call function to calculate factorial of 4, then 4 value is passed and it will be decreased by 1 until its value is 1, when n will be 1 then value will be returned after calculating desired value.
So i think in each case result should be 1, so how is it returning correct value.
Please clear.
Thanks in advance.
Best Regards,
Asif.





Re: Factorial Function Confusing. [message #677694 is a reply to message #677690] 
Mon, 07 October 2019 11:01 
Solomon Yakobson
Messages: 3152 Registered: January 2010 Location: Connecticut, USA

Senior Member 


In addition, function can be optimized a bit to reduce recursion level:
CREATE OR REPLACE function factorial (
n positive
) return positive
is
begin
if n <= 2 then
return n;
else
return N * factorial(n1);
end if;
end;
/
SY.




Re: Factorial Function Confusing. [message #677698 is a reply to message #677697] 
Tue, 08 October 2019 00:38 

Michel Cadot
Messages: 68264 Registered: March 2007 Location: Nanterre, France, http://...

Senior Member Account Moderator 


You missed this one:
return N * factorial(n1);
If N=1 then it returns 1 but if n <> 1 then it returns N multiplies by factorial(n1).
If you put the computation of your factorial(4) call you get:
4 * factorial(3) * factorial(2) * factorial(1) (and this later is 1)
[Updated on: Tue, 08 October 2019 00:41] Report message to a moderator





Goto Forum:
Current Time: Thu Aug 18 12:40:06 CDT 2022
