Why I am not getting any Exception in the following code? After running this code I am getting an infinite loop mentioning at test.fact(t.java:32) No Compile-Time Error was found.
class test
{
int fact(int m) throws Exception
{
if (m==1)
{
return 1;
}
else
return (fact ((m-1)*m));
}
}
class main
{
public static void main(String ar[]) throws Exception
{
test t = new test();
System.out.println(t.fact(5));
}
}
while say for example i am using
return(a+b);
it executes successfully whats the problem with the recursion to show an error???
You have a mistake in the return value expression of fact method. It should be
return fact(m-1) * m;
return (fact ((m-1)*m));
returns
fact(20)
which returns
fact (380)
which returns
fact (379*380)
which ....
which never returns anything and should make a stack overflow (too much memory is used on the call stack).
return fact(m-1) * m;
should work.
I highly recommend you reading again the basics, and examples ( here, for example - http://www.toves.org/books/java/ch18-recurex/index.html )
Try writing the recursion tree yoursels, in order to understand what happens.
Another way to calculate factorial using cycle (with no recursion):
int fact(int m) throws Exception
{
int f = 1;
for (int i = 0; i < m; f *= ++i);
return f;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.