Here is I have a factorial code using recursion.
class Factorial
{
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println(f.fact(Integer.parseInt(args[0])));
}
private int fact(int num)
{
int result;
if(num == 1)
return 1;
result = fact(num - 1) * num;
return result;
}
}
Now to run this program, I did this
D:\>java Factorial 3
Now according to the logic when it enters the fact function, where num = 3, so it will skip to
result = fact(num - 1) * num;
Here it will become
result = fact(3 - 1) * num;
i.e. result = fact(2) * num;
In this step, I am little confused Does it execute whole step i.e.
result = fact(num - 1) * num;
or just the fact(num - 1)
According to the logic, what it should do is call the fact function. So, the control of the program again reaches to the start of the fact function where num = 2. It will again skip to
result = fact(num - 1) * num;
So, it will become
result = fact(2 - 1) * num;
i.e. result = fact(1) * num;
Now again, it should call the fact function without executing the whole syntax & again reaches to the start of the fact method where num = 1. This time num == 1 will be matched & 1 will be returned. Now it will return to
result = fact(num - 1) * num;
So, it will become
result = fact(1 - 1) * num;
i.e. result = fact(0) * num;
Now what will happen next ?
Am I going right ? If not what will be the correction ?
I dont clearly understand the flow of this recursion program.
So, it will become
result = fact(1 - 1) * num;
Nope. For num = 2,
result = fact(num - 1) * num;
becomes
result = 1 * num; // i.e. 1 * 2
fact returns a value, which means the entire call has to be replace with that value.
Not sure why you would even think num changes at all. You have no num = ... in your code.
I added some trace into the program. Execute it and see the output. Should be easy to follow.
package snippet;
class Factorial {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println(f.fact(Integer.parseInt("5")));
}
private int fact(int num) {
int result;
if (num == 1)
return 1;
result = fact(num - 1) * num;
System.out.println("fact(" + num + ") = " + result + " = fact(" + (num - 1) + ") * " + num);
return result;
}
}
fact(2) = 2 = fact(1) * 2
fact(3) = 6 = fact(2) * 3
fact(4) = 24 = fact(3) * 4
fact(5) = 120 = fact(4) * 5
120
Your logic is right but you have made 3 basic errors.
if we take your example;
First you run the program
D:\>java Factorial 3
then you have your first mistake because according to the logic all "num" have to be replaced by "3". So you get:
result = fact(3 - 1) * 3;
ie:
result = fact(2)*3;
then we have the second mistake because according to the definition of fact(num),
fact(2) = fact(2-1)*2
so we actually have
result = (fact(2-1)*2)*3
which is evaluated in
result = (fact(1)*2)*3
and here stand the third mistake because again according to fact(num) definition : fact(1) = 1 and not fact(1) = fact(1-1)*1
so we finally have:
result = ((1)*2)*3
To be more explicit if you follow all call sequence in the debugger you 'll have something like this( I put between brackets the value of the variable):
private int fact(num{3})
{
int result;
if(num{3}== 1)
return 1;
result = fact(num{3} - 1) * num{3};
private int fact(num{3-1})
{
int result;
if(num{3-1}== 1)
result = fact(num{3-1} - 1) * num{3-1};
private int fact(num{3-1-1})
{
int result;
if(num{3-1-1}== 1)
return 1;
}
return result{1*{3-1}};
}
return result{{1*{3-1}}*3};
}
Unless we hit the stop condition:
fact(num) = fact(num - 1) * num;
Therefore:
fact(3) = fact(3 - 1) * 3;
Keeping in mind that fact(1) = 1 (from the if statement early in the fact() method):
fact(3) = fact(2) * 3;
fact(2) = fact(1) * 2;
fact(1) = 1;
Replacing each element:
fact(3) = 1 * 2 * 3;
The recursion is used to repeatedly dive deeper into the process until a stop condition is encountered - in this case when num = 1.
The call f.fact(3) is expanding through the following steps:
1. result = fact(3 - 1) * 3 = fact(2) * 3
2. result = (fact(2 - 1) * 2) * 3 = (fact(1) * 2) * 3
3. result = 1 * 2 * 3 because fact(1) returns 1.
Your implementation is correct, But it will never reach fact(1-1) * 1 state ,as you return from method at if(num == 1).
num variable is limited to scope of method parameter. So for every call to fact method num variable is assigned a new value (i.e. num-1) and which is limited to that parameter scope only. So when fact(num-1) returns , value of num will be the original value and not the num-1.
The flow of your example is like this
step 1. fact(3)*3; //calling the function with num value 3
step 2. fact(2)*2; //calling fact() method again with num=2
step 3. fact(1)*1; //now num == 1 will be matched & 1 will be returned.
i. e.,
1 * 1 = 1; //now, steps 2 and 1 will be performed respectively
step 2. 1 * 2 = 2;
step 1. 2 * 3 = 6;
So, the final answer will be 6
Note: In step 3, the value is returned, so it will not again call this result = fact(0) * num; //which you have mentioned in question.
Related
The actual operation is performed in the line return
return (num == 1 ? 1 : num * firstFactorial(num - 1 ) );
How we get 40320 for num 8?
public class Factorial {
public static int firstFactorial(int num) {
return (num == 1 ? 1 : num * firstFactorial(num - 1 ) );
}
public static void main(String[] args) {
System.out.println(firstFactorial(8));
}
}
There are multiple things happening in that return statement. One could rewrite the firstFactorial function like this:
public static int firstFactorial(int num) {
if (num == 1) {
return 1;
}
int decreased = num - 1;
int recursiveFactorial = firstFactorial(decreased);
int result = num * recursiveFactorial;
return result;
}
First of all this is using a technique called recursion. The function is calling itself with the number parameter decreased by one. You can think of it like this:
1. You call firstFactorial with value of 8
2. firstFactorial(8) calls itself with a value of 7
3. firstFactorial(7) calls itself with a value of 6
...
8. firstFactorial(2) calls itself with a value of 1
9. firstFactorial(1) returns 1 because of the if-statement
After calling itself the function multiplies the return value of the recursive call with its own parameter and returns it. So it will go on like this:
10. firstFactorial(2) multiplies 1 with 2 and returns 2
11. firstFactorial(3) multiplies 2 with 3 and returns 6
10. firstFactorial(4) multiplies 6 with 4 and returns 24
...
14. firstFactorial(8) multiplies 5040 with 8 and returns 40320 to you
All together this will calculate the faculty of the value like this: 8 * 7 * 6 * ... * 1
The rest is more or less coding style and syntactic sugar.
You don't need local variables and perform the call and the operations in one line:
public static int firstFactorial(int num) {
if (num == 1) {
return 1;
}
return num * firstFactorial(num -1);
}
Then there is the ternary conditional operator in java (<cond> ? <true statement> : <false statement>) which allows you to express the whole function body in one line:
public static int firstFactorial(int num) {
if (num == 1) {
return 1;
}
return (num == 1) ? 1 : (num * firstFactorial(num -1));
}
This is my code, I need an explanation of how this code works result=fact(n-1)*n;.My expected answer was not same as the output.I think after the return the stack should executing resumed state,the first execution state is
n=2 and (2-1)*2=2, then n=3,(3-1)*3=6, then n=4,(4-1)*4=12, then n=5,(5-1)*5=20.
The final answer I expected is 20. How did I get 120? How is the stack working in this scenario?. Thanks in advance.
public class Factorial
{
int fact(int n)
{
int result;
if(n==1) return 1;
result=fact(n-1)*n;
System.out.println("value of n="+n);
System.out.println(result);
return result;
}
}
class TestFact
{
public static void main(String[] args)
{
Factorial ob=new Factorial();
System.out.println("Final="+ob.fact(5));
}
}
The output of the given program is
value of n=2
2
value of n=3
6
value of n=4
24
value of n=5
120
Final=120
You misunderstood the method of calculating the factorial.
The method is defined as below for every n >= 1:
Cases:
fat(1) = 1 (by definition)
fat(2) = 2 * fat(1) (result on item 1) = 2 * 1 = 2
fat(3) = 3 * fat(2) (result on item 2) = 3 * 2 = 6
fat(4) = 4 * fat(3) (result on item 3) = 4 * 6 = 24
fat(5) = 5 * fat(4) (result on item 4) = 5 * 24 = 120
The algorithm is correct. You just misunderstood how factorial is calculated.
Improved code for better outputting
public class Factorial{
int fact(int n) {
int result;
if(n==1) return 1;
result=fact(n-1)*n;
System.out.println("Fat(" + n + ")=" + result);
return result;
}
public static void main(String[] args){
Factorial fat = new Factorial();
System.out.println("Final=" + fat.fact(5));
}
}
Try it online!
Your assumption is completely wrong.
Results of fact() function is 1, 2, 6, 24. So to get final result you need to multiply 1*2*6*24=120.
See recursion
Below is the solution to, and output of,the subject puzzle, and I'm having trouble understanding how it works.
public class Puzzle4 {
public static void main(String[] args) {
Puzzle4b[] obs = new Puzzle4b[6];
int y = 1;
int x = 0;
int result = 0;
while (x<6) {
obs[x] = new Puzzle4b();
obs[x].ivar = y;
y = y*10;
x = x+1;
}
x = 6;
while (x>0) {
x = x-1;
result = result + obs[x].doStuff(x);
}
System.out.println("result " + result);
}
}
class Puzzle4b {
int ivar;
public int doStuff(int factor) {
if (ivar>100) {
return ivar*factor;
} else {
return ivar*(5-factor);
}
}
}
Output:
result 543345
From my understanding, the first While loop will run through 6 times (from x==0 to x==5). The y variable, and in turn 'ivar', will have a value of 1,000,000 (I think this is where I'm going wrong, but I'll continue in hopes of being corrected).
The second While loop is a bit confusing to me. It'll run through 6 times, with the second line of the loop passing the 'x' values to the doStuff method for it to return a value. The numbers I'm coming up with for the result don't match the actual result.
Any help here would be appreciated. Please let me know if I'm thinking about it the wrong way. If someone wants to reformat my code to align more closely with industry standards, it would be great to learn good habits from the start!
this piece of code `
obs[x].ivar = y;
y = y*10;
will cause first ivar = y = 1 then multiple y
so it'll be {1 - 10 - 100 - 1,000 - 10,000 - 100,000}
the second loop x will be { 5 , 4 , 3 , 2 , 1 , 0 }
so it'll start like this result = result+obs[5].doStuff[5];
i guess all the misunderstanding that x in element 1 will equal y in element 5
and x in element 2 will equal y in element 4 and so on " because x is incrementing and y is decrementing
so it will go like this
(ivar > 100 )
ivar * (5-factor)
x[3] * y[2] = 1000 * (5-2) = 3000
x[4] * y[1] = 10000 * (5-1) = 40000
x[5] * y [0] = 100000 * (5-0) = 500000
then (ivar < 100)
ivar * factor
x[1] * y [5] = 1 * 5 = 5
x[2] * y [4] = 10 * 4 = 40
x[3] * y [3] = 100 * 3= 300
then if you add all the numbers together you'll have your output
In the second while loop,
while(x>0) will give 543340
Instead While (x>=0) should give the required output
If I'm not wrong
For me an easy way to break this down is stepping through and seeing exactly where the values are coming from. I've done this below and commented it into the code.
public class Puzzle4 {
public static void main(String[] args) {
Puzzle4b[] obs = new Puzzle4b[6];
int y = 1;
int x = 0;
int result = 0;
// let's break out of the loops
obs[0] = new Puzzle4b();
obs[0].ivar = 1;
obs[1] = new Puzzle4b();
obs[1].ivar = 10;
obs[2] = new Puzzle4b();
obs[2].ivar = 100;
obs[3] = new Puzzle4b();
obs[3].ivar = 1000;
obs[4] = new Puzzle4b();
obs[4].ivar = 10000;
obs[5] = new Puzzle4b();
obs[5].ivar = 100000;
// ivar's = 1, 10, 100, 1000, 10000, 100000
result = result + obs[5].doStuff(5); // 0 + (5 * 100000)
result = result + obs[4].doStuff(4); // 500000 + (4 * 10000)
result = result + obs[3].doStuff(3); // 540000 + (3 * 1000)
result = result + obs[2].doStuff(2); // 543000 + ((5 - 2) * 100)
result = result + obs[1].doStuff(1); // 543300 + ((5-1) * 10)
result = result + obs[0].doStuff(0); // 543340 + ((5-0) * 1)
// result = 543345
}
System.out.println("result " + result);
}
}
class Puzzle4b {
int ivar;
public int doStuff(int factor) {
if (ivar>100) {
return ivar*factor;
} else {
return ivar*(5-factor);
}
}
}
Hope this has helped you understand the example.
The key is to understand what each loop does.
1st one is nothing but just assigning values to ivar variable of each array object. You do it with "x" value as index.
2nd one you still get indices from what "x" variable currently is. And then you need to remember what ivar value is for exactly this index. With that in mind you will be able to understand what condition of doStuff method is true and what expression you should use respectively.
Also, you have to remember of what value "result" variable get on each loop iteration. Like 1st iteration result = 500 000. then 2nd one will be result = 500 000 + doStuff.
And last but not least, not without reason the book calls you to do exercises on paper. It leads to a lot of writing but also to understanding what code does on each and every line.
I created two recursive methods to calculate factorial as follows:
private int fact1(int n) {
if (n == 0 || n == 1)
return 1;
return n * fact1(--n);
}
private int fact2(int n) {
if (n == 0 || n == 1)
return 1;
return fact2(--n) * n;
}
When I call fact1(4) it returns 24. When I call fact2(4) it returns 6 (EDIT: is not returning 18 but 6). I know the second method is making 3 * 2 * 1, but I don't understand why not 4 * 3 * 2 * 1.
The same happens if I change the return to
//fact3(4) returns 60.
return (n + 1) * fact3(--n); // wrong
//fact4(4) returns 24
return fact4(--n) * (n + 1); // works
Why is the method exhibiting this behavior??
The question is about the different behaviour. I know n * fact(n-1) is the better way to solve it.
Can someone help me to understand the evaluation of this expression? Thanks!
It all comes down to the difference between these expressions:
return n * f(--n);
return f(--n) * n;
When n = 4, these expressions are evaluated like this:
return 4 * f(3);
return f(3) * 3;
Because the moment --n is evaluated, the value of n is decreased by 1.
This is how the prefix -- operator works.
It might help to recursively evaluate the entire expressions by hand. The first one:
// first
return 4 * f(3);
return 4 * 3 * f(2);
return 4 * 3 * 2 * f(1);
return 4 * 3 * 2 * 1;
// second
return f(3) * 3;
return f(2) * 2 * 3;
return f(1) * 1 * 2 * 3;
return 1 * 1 * 2 * 3;
On a related note, guess how this will be evaluated:
return f(n--) * n;
It will be:
return f(4) * 3;
Because here the postfix -- operator is used: the -1 decrement will be applied after the evaluation of n in f(...).
Here is a recursive static method in Java.
public static int mystery(int m, int n) {
int result = 1;
if (m > 0) {
result = n * mystery(m-1, n);
}
System.out.println (m + " " + result);
return result;
}
What will be printed to the standard output if we make the method call mystery(3,4)? What would be the final return value from the call to mystery(3,4)?
What is the explanation to the answer for the standard output part.
Output:
0 1
1 4
2 16
3 64
The final return value is 64.
Consider n to be fixed (which for all intents and purposes it is) and let f(m) be mystery(m,n).
Then
f(0) = 1
f(1) = n * f(0) = n
f(2) = n * f(1) = n * n
f(3) = n * f(2) = n * n * n
Can you see the general pattern? Can you give a closed form for f(n)?
Given your code which is
public static int mystery(int m, int n) {
int result = 1;
if (m > 0) {
result = n * mystery(m-1, n);
}
System.out.println (m + " " + result);
return result;
}
Lets start with m = 3 and n = 4, lets try to emulate it by trying to be the debugger...
mystery(3,4){
int result = 1
if(3 > 0){
result = 4 * mystery(3-1,4);
//We proceed from this point only after evaluating mystery(2,4)
mystery(2,4){
int result = 1
if(2 > 0){
result = 4*mystery(2-1,4);
//Now we have to evaluate mystery(1,4)
mystery(1,4){
int result = 1;
if(1 > 0){
result = 4*mystery(1-1,4);
//Evaluate mystery(0,4)
mystery(0,4){
int result = 1;
if(0 > 0){
//Not evaluated
}
System.out.println(0 + " "+1);
return 1;
}...mystery(0,4) done continue with evaluation of mystery(1,4)
result = 4*1 //1 is what is returned by mystery(0,4)
System.out.println(1+ "" + 4);
return 4;
}//done with the evaluation of mystery(1,4), resume evaluation of mystery(2,4)
result = 4*4 //4 is the value returned by mystery(1,4)
System.out.println(2 + " " + 16);
return 16;
}//At this point we are done with evaluating (2,4) and on the way to resume evaluation of mystery(3,4)
result = 4 * 16
System.out.println(3 + " "+ 64)
return 64;
}
}
Hope this helps
This sample calculates m to the power n.
So in your case the value is 64.
However have you tried it out and did analysis on your part?
The first call is mystery(3,4) which then calls mystery(2,4) which then calls mystery(1,4) which then calls mystery(0,4). In this example, the base case is mystery(0,4), i.e. m > 0 evaluates to false and result = n*mystery(m-1,n) will not get executed (recursion terminates here). Your base case is on top of the call stack and the bottom of your stack is mystery(3,4). Evaluate from the top of the call stack towards the bottom…