Reputation: 1438
I have this recursive factorial function:
public class Driver{
public static void main (String args[])
{
System.out.println(factorial(5));
}
private static int factorial(int n)
{
int product;
if (n <= 2){ product = n; return 2;}
else{
product = n * factorial(n-1);
System.out.println("current product =" + product);
System.out.println("product = " + n + " * factorial(" + (n-1) + ")");
}
return product;
}
}
It prints the following:
current product =6
product = 3 * factorial(2)
current product =24
product = 4 * factorial(3)
current product =120
product = 5 * factorial(4)
120
I'm trying to figure out what the heck is going on here. I don't understand how it starts printing for n = 2. And where did current product = 6 come from? Thanks!
Upvotes: 1
Views: 63
Reputation: 31952
n==2
is your base case, so the first function to get past the below line is the one where n-1 == 2
or n == 3
. This is because your output is performed after the recursive call, so it prints the deepest call first (thanks Patricia Shanahan) . If you want it to print from big to small, move your println
lines above the line which calls factorial
recursively.
product = n * factorial(n-1);
Also,
if (n <= 2){ product = n; return 2;}
This is wrong for so many reasons..
It should be
if (n <= 1){ return 1;}
If you are having trouble understanding this, remember that each call of factorial is independent of other calls.
Upvotes: 4