What is wrong with this java code, why is it not printing Factorial?
-
class facto
{
public static void main(String args[])
{
System.out.println(dust(5));
}static int dust(int z) { if (z==1||z==2) { return 2; } else { return dust(z-1) \* dust(z-2); } }
}
-
class facto
{
public static void main(String args[])
{
System.out.println(dust(5));
}static int dust(int z) { if (z==1||z==2) { return 2; } else { return dust(z-1) \* dust(z-2); } }
}
-
Firstly, you never print any of the interim values, and secondly, your calculations are wrong. See Fibonacci numbers[^]
I wanted to print Factorial. So, I am sorry for the mistake in the question.
-
I wanted to print Factorial. So, I am sorry for the mistake in the question.
Your calculation is still wrong.
f(1) === 1
, but your code returns2
. Andf(n) === n * f(n-1)
, but your code is returningf(n-1) * f(n-2)
. Also, unless this is a homework question to test your ability to write recursive functions, it's much more efficient to use a loop to calculate factorials or the Fibonacci sequence.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-
class facto
{
public static void main(String args[])
{
System.out.println(dust(5));
}static int dust(int z) { if (z==1||z==2) { return 2; } else { return dust(z-1) \* dust(z-2); } }
}
Maybe you shouldn't give the factorial of 1 the value 2 as it is returning in your first "if" construct. Now I am not expert but I think this should work:
public class facto{
public static void main(String[] args){
System.out.println(dust(5));
}static int dust(int n)
{
int output;
if(n==1){
return 1;
}output = dust(n-1)\* n; return output;
}
}I suppose that in your version the recursion is not able to complete properly because of "maybe" your trying to both return the value and calculate it at the same time. Hope the code snippet helps, I am just a beginner myself so apologies if I didn't get it right. P.S I know I haven't considered the condition of the input being 0.