Results 1 to 4 of 4
- 12-03-2012, 04:06 PM #1
Member
- Join Date
- Oct 2012
- Posts
- 5
- Rep Power
- 0
Factorial - java.lang.stackoverflow? Where's the mistake?
Hey Guys, I get the following error, when I'm trying to use the following method:
Error:Java Code:public long fak(int n) { if((n==1)||(n==0)) { return 1; } else { return (fak(n)); } }
java.lang.stackoverflowerror:
null
When I use the code like this, it works... but I don't understand why the Code on top should lead to a Loop or something similar...
Thank you for your help!Java Code:public long fak(int n) { if((n==1)||(n==0)) { return 1; } else { return (n*fak(n-1)); } }
- 12-03-2012, 04:18 PM #2
Senior Member
- Join Date
- Jun 2007
- Location
- Bali, Indonesia
- Posts
- 696
- Rep Power
- 6
Re: Factorial - java.lang.stackoverflow? Where's the mistake?
As you can see in your code the recursive call to fak(n) will never stop if n != 0 or n != 1. When you do something like fak(10) it will repeating the call to fak(10) until you run out of memory. Because the value of n is never change.
Website: Learn Java by Examples
- 12-03-2012, 04:28 PM #3
Member
- Join Date
- Oct 2012
- Posts
- 5
- Rep Power
- 0
- 12-03-2012, 06:05 PM #4
Moderator
- Join Date
- Apr 2009
- Posts
- 10,476
- Rep Power
- 16
Re: Factorial - java.lang.stackoverflow? Where's the mistake?
It does mean "give me the Value of fak(n)", but before it can give you that value it has to actually run fak(n), which will result in it getting to the same line, which results in another call to fak(n) to find the answer...and so on, down the rabbit hole.
And fak(4-1) does what?Please do not ask for code as refusal often offends.
Similar Threads
-
factorial java thread problem
By alwan2009 in forum New To JavaReplies: 14Last Post: 03-18-2012, 04:23 PM -
Factorial in java
By spidey32 in forum New To JavaReplies: 18Last Post: 04-09-2011, 01:04 PM -
factorial sum in java
By java157 in forum New To JavaReplies: 9Last Post: 03-17-2011, 10:07 AM -
StackOverFlow
By s0meb0dy in forum New To JavaReplies: 1Last Post: 02-17-2011, 06:50 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks