0

today 1st time i'm trying ot learn recursion funtion thru online tutorails but stuck at begining stage. i found below code but anything i give value its provide me output: 1
so, i need better explanation of that:

function factorial($n){

    if($n==0){
        return 1;
        }
    return fact($n, 1);
    }

    function fact($i, $j){

        if($i<1){
            return 1;}
            else {
            return fact($i-1, $i*$j);

            }

        }

echo factorial(5);

one more thing, i need clarification of how return fact($i-1, $i*$j); will work to convey single value from two paramaters. any1 pls give me some ideas regading this issue to give up my confusion.

2
Contributors
1
Reply
3
Views
4 Years
Discussion Span
Last Post by blocblue
0

You're nearly there. You weren't multiplying the original number by the resulting factor.

Also, you can simplify your code into a single function. E.g.

function factorial($number, $count = 1)
{
    if($number)
        return $number * factorial($number - 1, ($number - 1) * $count);

    return 1;
}

echo factorial(5);
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.