Konstruktionsplan's avatar

Recursive ♻️Factorial

Hello again! 👋🏻

This code I have written and understood. The idea came to me when I tried to solve it with a "for" loop.

Is that a "clean code"? I've heard about recursion many times, but until now I didn't call the function again and again, because the thing with the "Allowed memory size" without the if-block scared me! 👻

Thanks! 💜

function recursive_factorial($int) {
  	if ($int == 0) {
	   return 1;
	}
  
	return recursive_factorial($int-1) * $int;
}

print_r(recursive_factorial(5)); // 1 * 2 * 3 * 4 * 5
120
0 likes
11 replies
MichalOravec's avatar

@ravish What's the difference from his code?

A recursive function is a function that calls itself. If the function keeps calling itself, how does it know when to stop? You have to set up a condition, known as a base case. Base cases tell our recursive call when to stop, otherwise it will loop infinitely.

1 like
gitwithravish's avatar

@michaloravec How will my function keep looping infinitely? The condition is already set. It works just fine. And there is no difference between his and mine function, I just wrote it in less lines.

1 like
MichalOravec's avatar

@ravish What I posted is a generel thing what has to be done in the recursive function.

The question for you was why you posted that, when it's the same.

Konstruktionsplan's avatar

Hello friends!

The more code, the better, even if it is not the same code, right?

What @ravish posted seems to me to be a method in a class, while mine is a function. But of course the same in principle.

The question was whether the recursion itself is "clean code". :)

Konstruktionsplan's avatar

@michaloravec

"I've heard about recursion many times, but until now I didn't call the function again and again, because the thing with the "Allowed memory size" without the if-block scared me!"

If I don't catch an error somewhere, it will crash on a live server, but it will not paralyze it. But if I start an "infinite call", it will crash much more, right?

Sinnbeck's avatar

You will just get this error :)

Error
Maximum function nesting level of '256' reached, aborting!

Give it a try yourself

Route::get('recurse', function () {
    function myrecurse() {
        return myrecurse();
    }

    return myrecurse();
});
1 like
MichalOravec's avatar

No, it depends what you have set in php.ini for max_nesting_level

It's a PHP related things.

1 like
Sinnbeck's avatar

I actually believe that it is xdebug that catches it :) You can give it a try on your local testing environment. Without xdebug you would most likely just run out of memory and the thread would be closed.

Please or to participate in this conversation.