Results 1 to 7 of 7
Thread: Recursion problem
 10062010, 12:17 AM #1Member
 Join Date
 Sep 2010
 Posts
 62
 Rep Power
 0
Recursion problem
I want to practice want I learned/didn't learn about recursion. I think I didn't learn much but I don't give up.
Here I want to calculate n*n + (n1)*(n1) + (n2)*(n2) + ... etc. using recursion.
Java Code:static long sum( int n ) { if( n == 0 ) return 0; //base case else { return (n*n) + sum(n1)*(n1); }
I thought the above code was correct in order to give me the desired result but it is not. When I input for example 5 result is 317.
I tracked variable n. It does go 54321012345 but the result is not 55.
Any ideas would be greatly appreciated.
 10062010, 12:50 AM #2Moderator
 Join Date
 Feb 2009
 Location
 New Zealand
 Posts
 4,712
 Rep Power
 13
return (n*n) + sum(n1)*(n1);
That line doesn't look right. It's saying "figure out n squared, then add that to the sum of the squares up to (n1) multiplied by (n1)". Why that last bit?
 10062010, 12:59 AM #3Member
 Join Date
 Sep 2010
 Posts
 62
 Rep Power
 0
Last edited by luke; 10062010 at 01:05 AM.
 10062010, 01:32 AM #4Moderator
 Join Date
 Feb 2009
 Location
 New Zealand
 Posts
 4,712
 Rep Power
 13
I'm not sure if you've got this problem solved or not. (And I am deliberately loathe to provide code as this would defeat the whole purpose of the question.)
Here is your method rewritten with a more descriptive method name:
Java Code:static long sumOfSquaresUpTo(int n) { if(n == 0) return 0; //base case else { return (n*n) + sumOfSquaresUpTo(n1) *(n1); }
And I'm wondering if you can see why that last multiplication is wrong.
After all thesumofsquaresupto n is just n squared plus thesumofsquaresupto (n1).
 10062010, 03:02 AM #5Member
 Join Date
 Sep 2010
 Posts
 62
 Rep Power
 0
 10062010, 06:14 AM #6Moderator
 Join Date
 Feb 2009
 Location
 New Zealand
 Posts
 4,712
 Rep Power
 13
Great. Glad to help.
 10062010, 06:35 AM #7Member
 Join Date
 Sep 2010
 Posts
 62
 Rep Power
 0
Similar Threads

more fun... with recursion
By sonny in forum New To JavaReplies: 19Last Post: 03232010, 06:09 AM 
recursion and tailrecursion differences
By OptimusPrime in forum New To JavaReplies: 2Last Post: 12282009, 07:26 PM 
recursion and call stack problem
By OptimusPrime in forum New To JavaReplies: 4Last Post: 12262009, 10:49 PM 
Java Recursion Problem
By gmnnn in forum Threads and SynchronizationReplies: 1Last Post: 12062009, 05:22 PM 
help with recursion
By Nari in forum New To JavaReplies: 15Last Post: 04242008, 09:13 AM
Bookmarks