+ 1
Help me to understand this code, please
Hi all, Can someone please explain me how does this code work? ---- <?php function func($num, $ch="sum") { if ($num == 1) return 1; else { if ($ch == "factorial") return $num * func($num - 1, $ch); else return $num + func($num - 1, $ch); } } echo func (5); echo func (5,"factorial"); ?> ---- I am looking at this for 2 days already and I can't get anything. Why we get 15120 as a result??? I can't understand what is happening after the first "else" and till the end... I know how factorial should be calculated, but this is some another thing. I would appreciate any detailed explanation of these strings... Thank you!
4 Respostas
+ 11
This is a question I submitted (I didn't think it would be approved but it was approved). Here's the solution.
The function takes a number and a string as input.
1) If input string is "factorial", the factorial of the input number is returned.
2) If input string is "sum", the sum of numbers till the input number is returned.
func(5) => input number is 5 and input string is "sum" (default). So, sum of numbers till 5 = 1+2+3+4+5 = 15 is returned.
func(5, "factorial") => input number is 5 and input string is "factorial". So, factorial of 5 = 5! = 120 is returned.
+ 4
I recognised that question!
Wait i think we have to remive linebreaks to get that
0
@S Vengat, just copy everything between ---- and ---- and it will work :)
0
Thank you, @Krishna, you are my Jesus Christ.