Results 1 to 6 of 6
Thread: Again recursion question
- 10-04-2010, 09:58 PM #1
Member
- Join Date
- Sep 2010
- Posts
- 62
- Rep Power
- 0
Again recursion question
I am trying to do recursion in order to solve a problem. Since my original code is not working correctly (I am not doing the recursion correctly) I decided to do recursion but for a simple problem in order to understand what exactly is going on.Java Code:public class Neper_number { static double factorial( int n ) { double result; if( n <= 0 ) return 1; else { result = 1 + (n * factorial(n - 1)); return result; } } }
With the above code I thought that for example if I input n = 2 I would get
result = 1 + 2! = 3; if n = 3 I would get result 1 + 3! = 1 + 3x2x1 = 7 and so on. But instead when I input n = 2 I am getting result = 5, when n = 3 I am getting result = 16 etc.
Does anybody know why that is?
- 10-04-2010, 10:03 PM #2
Don't add 1 here.Java Code:result = [color=red]1 + [/color](n * factorial(n - 1));
- 10-04-2010, 10:12 PM #3
Member
- Join Date
- Sep 2010
- Posts
- 62
- Rep Power
- 0
- 10-04-2010, 10:17 PM #4
Firstly, factorial never adds. 7! is 5040, not 5041. 3! is 6, not 7.
If you want the result of 1+!n, you cannot add it in that location because it's recursive (it will repeat this action as well as the others).
Work it out step-by-step using 4 as a value:
Java Code:factorial(4) -> result = 1 + (4 * factorial(3)) factorial(3) -> result = 1 + (3 * factorial(2)) factorial(2) -> result = 1 + (2 * factorial(1)) factorial(1) -> result = 1 + (1 * factorial(0)) factorial(0) -> return 1;
See how the "1 +" recurs over and over? That's where the problem is. Instead of doing that, you'd want something like:Java Code:Simplified, that's: factorial(4) = 1 + (4 * (1 + 3 * (1 + 2 * (1 + (1 * 1))))); factorial(4) = 1 + (4 * (1 + 3 * (1 + 2 * (1 + 1)))); factorial(4) = 1 + (4 * (1 + 3 * (1 + 2 * 2))); factorial(4) = 1 + (4 * (1 + 3 * (1 + 4))); factorial(4) = 1 + (4 * (1 + 3 * 5)); factorial(4) = 1 + (4 * 16); factorial(4) = 1 + 64; factorial(4) = 65; // Should be 1+4! == 1 + 4*3*2*1 == 1 + 24 == 25
Since this is not recursive, 1 will only be added once.Java Code:public static double FactorialPlusOne(int n) { return 1 + factorial(n); }
- 10-04-2010, 11:30 PM #5
Member
- Join Date
- Sep 2010
- Posts
- 62
- Rep Power
- 0
- 10-05-2010, 12:02 AM #6
Similar Threads
-
Recursion question
By luke in forum New To JavaReplies: 12Last Post: 10-04-2010, 10:04 PM -
Touch recursion question
By myst in forum New To JavaReplies: 18Last Post: 06-08-2010, 06:48 PM -
very simple Question
By arsenal4ever_11 in forum NetBeansReplies: 2Last Post: 05-27-2010, 08:51 PM -
some simple question?
By jperson in forum New To JavaReplies: 4Last Post: 05-03-2010, 05:32 PM -
Simple Question
By barusk in forum NetworkingReplies: 13Last Post: 03-04-2009, 07:33 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks