Results 1 to 6 of 6
Thread: Again recursion question
 10042010, 09:58 PM #1Member
 Join Date
 Sep 2010
 Posts
 62
 Rep Power
 0
Again recursion question
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?
 10042010, 10:03 PM #2Java Code:
result = [color=red]1 + [/color](n * factorial(n  1));
 10042010, 10:12 PM #3Member
 Join Date
 Sep 2010
 Posts
 62
 Rep Power
 0
 10042010, 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 stepbystep 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;
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
Java Code:public static double FactorialPlusOne(int n) { return 1 + factorial(n); }
 10042010, 11:30 PM #5Member
 Join Date
 Sep 2010
 Posts
 62
 Rep Power
 0
 10052010, 12:02 AM #6
Similar Threads

Recursion question
By luke in forum New To JavaReplies: 12Last Post: 10042010, 10:04 PM 
Touch recursion question
By myst in forum New To JavaReplies: 18Last Post: 06082010, 06:48 PM 
very simple Question
By arsenal4ever_11 in forum NetBeansReplies: 2Last Post: 05272010, 08:51 PM 
some simple question?
By jperson in forum New To JavaReplies: 4Last Post: 05032010, 05:32 PM 
Simple Question
By barusk in forum NetworkingReplies: 13Last Post: 03042009, 08:33 PM
Bookmarks