newday
newday

Reputation: 3878

How does return work in recursive?

Can we say that when $number <2 it doesn't call factirial() function again? Or it calls factorial() function but it always sets factorial to factorial(1). If so, I think recursive use more memory. Am I correct?

<?php function factorial($number){

                if ($number < 2) { 
                return 1; 
                } else { 
                return ($number * factorial($number-1)); 
                } 
            }

echo factorial(5);
?>

this is what I guess in the function

3*factorial(2)
2*factorial(1)
1*factorial(1)
1*factorial(1)

Upvotes: 0

Views: 94

Answers (1)

Forhad Ahmed
Forhad Ahmed

Reputation: 1771

Can we say that when $number <2 it doesn't call factirial() function again?

Yes

Upvotes: 1

Related Questions