Reputation: 13
I am having trouble making a recursive method that calculates the sum of 1,2,3 to N, but does it by adding (1,2,3... to N/2) with (N/2+1... to N).
The code i manage so far is this:
public static void main(String[] args) {
System.out.println(sum(10, 1));
}
public static int sum(int n, int start) {
if (start == n){
return n;
}
if (start > n / 2){
return start + sum(n, start + 1);
}
return start + sum(n, start + 1);
}
I believe this is wrong, It is an assignment in school where we have to motivate how splitting the recursion up into to parts is a more/lesser efficient way of calculating the sum. (adding numbers from 1 to N/2 with N/2 to N, instead of just from 1 to N directly).
He made us do this way to make it harder for us but i cannot grasp the idea on how to do this at all. Is it correct?
Thanks
Upvotes: 0
Views: 1267
Reputation:
I believe, that this piece of code is as simple as possible, you can check performance in a loop. I don't see any difference in complexity.
class Sums {
public static int sumHelp(int n, int start){
if (n == start) return;
else return (n + sumHelp(n - 1, start));
}
public static int sumByHalf(int n){
return sumHelp(n/2, 0) + sumHelp(n, n/2);
}
public static int sum(int n){
return sumHelp(n, 0);
}
public static void main(String[] args) {
System.out.println(sumByHalf(100));
System.out.println(sum(100));
}
}
Upvotes: 0
Reputation: 347
Check out that you got declare n as an int. n/2 not always will give to you the expected value. I think that's the trick your teacher wants you to observe.
Upvotes: -1
Reputation: 18803
Might be helpful in some cases to reduce recursion depth.
You need to take start into account when calculating n/2 for inner steps, the code should probably look similar to this:
public static int sum(int n, int start) {
if (start > n) {
return 0;
}
if (start == n){
return n;
}
int n2 = (start + n) / 2;
return sum(n2, start) + sum(n, n2 + 1);
}
The start > n check just avoids extra checks at the end for the case where start and n are less than 2 apart.
Upvotes: 2